p157 二叉树中的所有路径(leetcode 257)

一:解题思路

Time:O(n^2),Space:O(n^2)

二:完整代码示例 (C++版和Java版)

C++:

class Solution 
{
private:
    void dfs(TreeNode* root, string path, vector<string>& result)
    {
        if (root == NULL) return;
        path += to_string(root->val);
        if (root->left == NULL && root->right == NULL)
        {
            result.push_back(path);
        }
        else
        {
            path += "->";
            dfs(root->left,path,result);
            dfs(root->right,path,result);
        }
    }
public:
    vector<string> binaryTreePaths(TreeNode* root) 
    {
        vector<string> result;

        dfs(root,"",result);

        return result;
    }
};

Java:

class Solution
    {
        private void dfs(TreeNode root,String path,List<String> result)
        {
                if(root==null) return;
                path+=root.val;
                if(root.left==null && root.right==null)
                {
                    result.add(path);
                }
                else
                {
                    path+="->";
                    dfs(root.left,path,result);
                    dfs(root.right,path,result);
                }
        }

        public List<String> binaryTreePaths(TreeNode root)
        {
                List<String> result=new ArrayList<>();
                
                dfs(root,"",result);
                
                return result;
        }
    }

 

posted @ 2020-07-23 16:32  repinkply  阅读(194)  评论(0)    收藏  举报