力扣-二叉树-257 二叉树的所有路径

思路

除去根节点,每一层添加->val,然后使用前序遍历的顺序

代码

class Solution {
public:
    vector res;
    void getTreePaths(string s, TreeNode* root){
        s += "->";
        s += to_string(root->val);
        if(root->left == nullptr && root->right == nullptr){
             res.push_back(s);
             return;
        }
        
        if(root->left) getTreePaths(s, root->left);
        if(root->right) getTreePaths(s, root->right);

    }

    vector binaryTreePaths(TreeNode* root) {
        if(root->left == nullptr && root->right == nullptr){
            res.push_back(to_string(root->val));
            return res;
        }
        string s;
        if(root->left) getTreePaths(to_string(root->val), root->left);
        if(root->right) getTreePaths(to_string(root->val), root->right);

        return res;
    }
};

你可能感兴趣的:(力扣,#,二叉树,leetcode,算法)