Binary Tree Paths
lc 257
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"]
简练code
public List<String> binaryTreePaths(TreeNode root) {
List<String> answer = new ArrayList<String>();
if (root != null) searchBT(root, "", answer);
return answer;
}
private void searchBT(TreeNode root, String path, List<String> answer) {
if (root.left == null && root.right == null) answer.add(path + root.val);
if (root.left != null) searchBT(root.left, path + root.val + "->", answer);
if (root.right != null) searchBT(root.right, path + root.val + "->", answer);
}
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<String>();
if(root == null) return result;
List<String> left = binaryTreePaths(root.left);
List<String> right = binaryTreePaths(root.right);
if(left == null && right == null || left.size() == 0 && right.size() == 0){
result.add(String.valueOf(root.val));
return result;
}
for(String i : left ){
StringBuilder sb = new StringBuilder();
sb.append(root.val);
sb.append("->");
sb.append(i);
result.add(sb.toString());
}
for(String i : right){
StringBuilder sb = new StringBuilder();
sb.append(root.val);
sb.append("->");
sb.append(i);
result.add(sb.toString());
}
return result;
}