题目
Given a binary tree, return all root-to-leaf paths.
我的想法
遍历法,需要注意不能在root == null时把结果加入list,这样会重复计算,而且并没有走到真正的叶子结点(缺少一边的子树也会输出,但实际上这并不是叶子结点)
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new LinkedList<>();
if(root == null) {
return list;
}
helper("", root, list);
return list;
}
private void helper(String path, TreeNode root, List<String> list) {
if(root == null) {
return;
}
if(root.right == null && root.left == null) {
path += root.val;
list.add(path);
return;
}
path += root.val;
helper(path + "->", root.left, list);
helper(path + "->", root.right, list);
}
}
解答
jiuzhang solution: divide
一开始并没有想到怎样用分治来做,主要是智障的觉得从后往前路径会是反的,path是String直接在前方插入就好了啊!!!!
对于分治法来说可以直接做到root == null,这个有点像dp的bottom up,由若干个小数组(即路径)向上汇总成一个大数组
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new LinkedList<>();
if(root == null) {
return paths;
}
//store leftpaths, rightpaths
List<String> leftpaths = binaryTreePaths(root.left);
List<String> rightpaths = binaryTreePaths(root.right);
//add cur node to the leftpaths, rightpaths
//and integrate them to the cur node paths
for(String path : leftpaths) {
paths.add(root.val + "->" + path);
}
for(String path : rightpaths) {
paths.add(root.val + "->" + path);
}
if(paths.size() == 0) {
paths.add("" + root.val);
}
return paths;
}
}
jiuzhang solution: traversal
想法一样,写的更漂亮一些
public class Solution {
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<String>();
if (root == null) {
return result;
}
helper(root, String.valueOf(root.val), result);
return result;
}
private void helper(TreeNode root, String path, List<String> result) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
result.add(path);
return;
}
if (root.left != null) {
helper(root.left, path + "->" + String.valueOf(root.left.val), result);
}
if (root.right != null) {
helper(root.right, path + "->" + String.valueOf(root.right.val), result);
}
}
}