257、Binary Tree Paths

来源:互联网 发布:给淘宝差评怎么写 编辑:程序博客网 时间:2024/06/05 07:42

题目:

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

For example, given the following binary tree:

   1 /   \2     3 \  5

All root-to-leaf paths are:

["1->2->5", "1->3"]


解题思路:

树的DFS遍历。

python版本:

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def binaryTreePaths(self, root):        """        :type root: TreeNode        :rtype: List[str]        """        def dfs(root,path):            if(root.left==None and root.right==None):                self.ans.append(path)            if(root.left!=None):                dfs(root.left, path+'->'+str(root.left.val))            if(root.right!=None):                dfs(root.right, path+'->'+str(root.right.val))        self.ans = []        if(root!=None):            dfs(root,str(root.val))        return self.ans        


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> ans;        string dfs(TreeNode* root,string path){        if(root->left==NULL and root->right==NULL)            ans.push_back(path);        if(root->left)            dfs(root->left,path+"->"+to_string(root->left->val));        if(root->right)            dfs(root->right,path+"->"+to_string(root->right->val));    }        vector<string> binaryTreePaths(TreeNode* root) {        if(root!=NULL)            dfs(root,to_string(root->val));        return ans;    }};


0 0