leetcode-binary-tree-paths

题目大意

  https://leetcode.com/problems/binary-tree-paths/

  给你一棵二叉树,输出所有root节点到leaf节点的路径。

题目分析

  比较简单的递归。

代码

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private List<String> ans;
private void helper(TreeNode r, String path, int idx) {
if (r == null) {
return;
}
if (!path.equals("")) {
path += "->";
}
if (r.left == null && r.right == null) {
ans.add(path + r.val);
return;
}
helper(r.left, path + r.val, idx + 1);
helper(r.right, path + r.val, idx + 1);
}
public List<String> binaryTreePaths(TreeNode root) {
ans = new ArrayList<String>();
helper(root, "", 0);
return ans;
}
}