257. Binary Tree Paths

Total Accepted: 36923
Total Submissions: 135278
Difficulty: Easy

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"]

Java:

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
29
30
31
32
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void help(List<String> list, TreeNode node, StringBuilder sb) {
        if (node == null)
            return;
        int len=sb.length();
        sb.append(node.val);
        if (node.left == null && node.right == null) {                
            list.add(sb.toString());
            sb.setLength(len);
            return;
        }
        sb.append("->");
        help(list, node.left, sb);
        help(list, node.right, sb);
        sb.setLength(len);
    }

    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<String>();
        help(res, root, new StringBuilder());
        return res;
    }
}

打个小广告

欢迎加入我的小专栏「基你太美」一起学习。