Binary Tree Paths
Question:
Given a binary tree, return all root-to-leaf paths.
Example
Given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
[
"1->2->5",
"1->3"
]
Lesson Learned
Code:
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
private StringBuilder s;
private List<String> lists;
public List<String> binaryTreePaths(TreeNode root) {
s = new StringBuilder();
lists = new ArrayList<String>();
helper(root);
// donot forget return
return lists;
}
public void helper(TreeNode root) {
// Write your code here
if (root == null) {
return;
}
s.append("->");
s.append(root.val);
if (root.left == null && root.right == null) {
String str = s.toString();
lists.add(str.substring(2, str.length()));
}
helper(root.left);
helper(root.right);
// delete not remove; delete(index start, index end)
// 有负数的情况所以不能只判断‘-’,必须判断‘->’
while (s.charAt(s.length() - 2) != '-' || s.charAt(s.length() - 1) != '>') {
s.delete(s.length()-1, s.length());
}
s.delete(s.length()-2, s.length());
}
}
Updated:
// you can pass whatever you want to the helper method
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
private String path;
private List<String> list;
public List<String> binaryTreePaths(TreeNode root) {
// Write your code here
list = new ArrayList<String>();
if (root == null) {
return list;
}
path = String.valueOf(root.val);
binaryTreePath(root, path);
return list;
}
// 让list做返回值特别不好,因为返回值一般是对下一轮有影响的,因此把list当做参数传递进来。
// 不传进来直接作为全局变量也是可以的。
// path是随路径变化的,因此作为传递函数
// list只向里面加东西,所以可以作为全局变量存在
private void binaryTreePath(TreeNode root, String path) {
if (root.left == null && root.right == null) {
list.add(path);
return;
}
if (root.left != null) {
binaryTreePath(root.left, path + "->" + root.left.val);
}
if (root.right != null) {
binaryTreePath(root.right, path + "->" + root.right.val);
}
}
}