Leetcode 257 Binary Tree Paths java

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

Example:
Input:

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

Output: [“1->2->5”, “1->3”]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

解答

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
33
34
35
36
public class L257 {
class TreeNode{
int val;
TreeNode left;
TreeNode right;

public TreeNode(int val) {
this.val = val;
}
}

List<String> resultList = new ArrayList<String>();

public List<String> binaryTreePaths(TreeNode root) {
deepSearch(root, new StringBuilder());
return resultList;
}
//用一个递归就odek
public void deepSearch(TreeNode root, StringBuilder stringBuilder) {
if(root == null)
return ;
if(root.left == null && root.right == null) {
stringBuilder.append(root.val);
resultList.add(stringBuilder.toString());
return ;
}

stringBuilder.append(root.val + "->");

if(root.left != null)
deepSearch(root.left, new StringBuilder(stringBuilder.toString()));
if(root.right != null)
deepSearch(root.right, new StringBuilder(stringBuilder.toString()));

}
}

感谢你对我的支持 让我继续努力分享有用的技术和知识点.