1. 程式人生 > 實用技巧 >p157 二叉樹中的所有路徑(leetcode 257)

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; } }