卖萌的弱渣

I am stupid, I am hungry.

Binary Tree Paths

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

For example, given the following binary tree:

1
2
3
4
5
   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

1
["1->2->5", "1->3"]
(Binary-Tree-Paths.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param {TreeNode} root
    # @return {string[]}

    def dfs(self,ret,path,node):
        path += str(node.val)
        if node.left == None and node.right == None:
            ret.append(path[:])
        path += "->"
        if node.left != None:
            self.dfs(ret,path,node.left)
        if node.right != None:
            self.dfs(ret,path,node.right)


    def binaryTreePaths(self, root):
        ret = []
        if root == None:
            return ret
        self.dfs(ret,"",root)
        return ret
  • Java:
(Binary-Tree-Paths.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> ret = new LinkedList<String>();
        if (root==null)
            return ret;
        searchBT(root,""+root.val,ret);
        return ret;
    }

    public void searchBT(TreeNode node, String path, List<String> ret){
        if (node.left==null && node.right == null)
            ret.add(path);
        if (node.left != null)
            searchBT(node.left, path+"->"+node.left.val, ret);
        if (node.right != null)
            searchBT(node.right, path+"->"+node.right.val, ret);

    }
}