LeetCode 257. 二叉树的所有路径

题目描述: 二叉树的所有路径

        给定一个二叉树,返回从根节点到叶节点的所有路径。

        例如,给定以下二叉树:

   1
 /   \
2     3
 \
  5

        所有根到叶路径是:

["1->2->5", "1->3"]

解题思路:

        递归到叶节点,然后push进vs,也没什么说的。注意vector要引用,string不要引用。

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> vs;
        if(root == NULL) return vs;
        string s;
        f(vs, s, root);
        return vs;
    }
    
    bool f(vector<string>& v,string s, TreeNode* root) {
        if(root == NULL) return true;
        if(s.empty()) s += to_string(root->val);
        else s += "->" + to_string(root->val);
        bool a, b;
        a = f(v, s, root->left);
        b = f(v, s, root->right);
        if(a&&b) v.push_back(s);
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_33168253/article/details/80058663
今日推荐