Binary Tree Paths 解答

时间:2023-03-09 02:32:42
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);
}
}