LeetCode Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

完美解法:

vector binaryTreePaths(TreeNode* root) {
        vector res;
        if(!root) return res;
        helper(root, res, to_string(root -> val));
        return res;
    }
    
    void helper(TreeNode* root, vector& res, string st) {
        if(root -> left == root -> right) {
            res.push_back(st);
            return ;
        }
        if(root -> left) helper(root -> left, res, st + "->" + to_string(root -> left -> val));
        if(root -> right) helper(root -> right, res, st + "->" + to_string(root -> right -> val));
    }

传参中传递一个st,到达叶子结点时可以直接压入结果,而如果像下面的解法,就很不优美了(叶子节点处理逻辑复杂)。

vector binaryTreePaths(TreeNode* root) {
        vector path;
        vector res;
        if(!root) return res;
        dfs(root, path, res);
        return res;
    }
    void dfs(TreeNode* root, vector& path, vector& res) {
        if(root -> left == root -> right){
            string tmp;
            path.push_back(root -> val);
            for(int i = 0; i";
            tmp += to_string(path[path.size()-1]);
            res.push_back(tmp);
            path.pop_back();
            return;
        }
        path.push_back(root -> val);
        if(root -> left) dfs(root -> left, path, res);
        if(root -> right) dfs(root -> right, path, res);
        path.pop_back();
    }

你可能感兴趣的:(LeetCode Binary Tree Paths)