之后的题都是用java,以练习java的语法和库的使用
我的算法,递归:
// List interface 问题
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
// 这个list用于存储所有可能的路径
List<String> paths = new ArrayList<String>();
//bound
if(root == null) return paths;
StringBuilder path = new StringBuilder("");
FindPath(root,paths,path);
return paths;
}
private void FindPath(TreeNode node, List<String> paths, StringBuilder path_){
StringBuilder path = new StringBuilder(path_.toString());
// current node is leaf
if(node.left == null && node.right == null) {
paths.add(path.append(String.valueOf(node.val)).toString());
return;
}
path = path.append(String.valueOf(node.val));
path = path.append("->");
// current node has a left node
if(node.left != null){
FindPath(node.left,paths,path);
}
// current node has a right node
if(node.right != null){
FindPath(node.right,paths,path);
}
}
}
在代码中我尝试着用 new List<>();
来实例化一个 List,但是报错,因为 List 是一个 interface 在 java.util
库中
但是我搜索到 List 是一个对象在 java.awt
中,这是与窗口界面相关的包
更优的算法
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> rst = new ArrayList<String>();
if(root == null) return rst;
StringBuilder sb = new StringBuilder();
helper(rst, sb, root);
return rst;
}
public void helper(List<String> rst, StringBuilder sb, TreeNode root){
if(root == null) return;
int tmp = sb.length();
if(root.left == null && root.right == null){
sb.append(root.val);
rst.add(sb.toString());
sb.delete(tmp , sb.length());
return;
}
sb.append(root.val + "->");
helper(rst, sb, root.left);
helper(rst, sb, root.right);
sb.delete(tmp , sb.length());
return;
}
}