1. 程式人生 > >257. Binary Tree Paths(python+cpp)

257. Binary Tree Paths(python+cpp)

題目:

Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:

Input:
   1  
 /   \ 
2     3  
 \   
  5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3

解釋:
返回二叉樹中所有從root到leaf的路徑,第一反應就是用dfs做。
python程式碼:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
if not root: return [] result=[] def dfs(root,s,result): if root.left==None and root.right==None: result.append(s) if root.left!=None: dfs(root.left,s+"->"+str(root.left.val),result) if root.right!=
None: dfs(root.right,s+"->"+str(root.right.val),result) if root: dfs(root,str(root.val),result) return result

c++程式碼:

/**
 * 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> result;
        if (root)
            dfs(root,to_string(root->val),result);
        return result;
    }
    void dfs(TreeNode* root,string s,vector<string>&result)
    {
        if (root->left==NULL &&root->right==NULL)
            result.push_back(s);
        if (root->left)
            dfs(root->left,s+"->"+to_string(root->left->val),result);
        if(root->right)
            dfs(root->right,s+"->"+to_string(root->right->val),result);
    }
};

總結:
就是很經典的dfs的題目,注意dfs的時候有些判斷是無意義的,去掉以後速度會有很明顯的提升哦,儘量在進入dfs之前先做好條件判斷,因為入棧還要花費一定的時間。