Binary Tree Paths 解答

Question

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

Solution -- Recursive

We can not apply inorder traversal here because it only show path from root to leaf node as required. Therefore, we use recursive way.

We consider two situation:

1. Current node is leaf. Add string to result.

2. Current node has children. Go on.

 /**
* 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> result = new ArrayList<String>();
if (root == null)
return result;
dfs(root, result, new StringBuilder());
return result;
} private void dfs(TreeNode root, List<String> result, StringBuilder current) {
if (root == null)
return;
if (root.left == null && root.right == null) {
current.append(root.val);
result.add(current.toString());
return;
} current.append(root.val);
current.append("->"); StringBuilder tmp1 = new StringBuilder(current);
StringBuilder tmp2 = new StringBuilder(current);
if (root.left != null)
dfs(root.left, result, tmp1);
if (root.right != null)
dfs(root.right, result, tmp2);
}
}
上一篇:ubuntu 安装fcitx输入法


下一篇:JVM(二)GC算法和垃圾收集器