
方法1: recursion。这里其实有两种recursion,一种是我自己写的bottom-up,还有一种是lc的答案top-down。这里很明显top-down要好,因为如果bottom-up的话就存在要copy children to parent这个操作,这个操作复杂度是logn,所以bottom-up会慢很多。总结一下:top-down时间复杂n,空间复杂logn。bottom-up时间复杂nlogn,空间复杂n^2.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
// bottom-up
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<>();
if(root == null) return list;
if(root.left == null && root.right == null){
list.add(Integer.toString(root.val));
return list;
}
if(root.left != null){
List<String> list1 = binaryTreePaths(root.left);
for(String s : list1){
s = root.val + "->" + s;
list.add(s);
}
}
if(root.right != null){
List<String> list2 = binaryTreePaths(root.right);
for(String s : list2){
s = root.val + "->" + s;
list.add(s);
}
}
return list;
}
}
// top-down
class Solution {
public void construct_paths(TreeNode root, String path, LinkedList<String> paths) {
if (root != null) {
path += Integer.toString(root.val);
if ((root.left == null) && (root.right == null)) // if reach a leaf
paths.add(path); // update paths
else {
path += "->"; // extend the current path
construct_paths(root.left, path, paths);
construct_paths(root.right, path, paths);
}
}
}
public List<String> binaryTreePaths(TreeNode root) {
LinkedList<String> paths = new LinkedList();
construct_paths(root, "", paths);
return paths;
}
}
方法2: iteration。时间复杂n,空间复杂n。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<>();
if(root == null){
return list;
}
Stack<TreeNode> node_stack = new Stack<>();
Stack<String> path_stack = new Stack<>();
node_stack.push(root);
path_stack.push(Integer.toString(root.val));
while(!node_stack.isEmpty()){
TreeNode node = node_stack.pop();
String path = path_stack.pop();
if(node.left == null && node.right == null){
list.add(path);
}
if(node.left != null){
node_stack.push(node.left);
path_stack.push(path + "->" + Integer.toString(node.left.val));
}
if(node.right != null){
node_stack.push(node.right);
path_stack.push(path + "->" + Integer.toString(node.right.val));
}
}
return list;
}
}
总结:
- 在做string contact的时候要避免+,我们要去使用stringbuilder。
博客介绍了两种处理方法,递归和迭代。递归有bottom - up和top - down两种,top - down时间复杂度为n,空间复杂度为logn;bottom - up时间复杂度为nlogn,空间复杂度为n^2。迭代时间复杂度为n,空间复杂度为n。还提醒做字符串拼接时用stringbuilder代替+。
430

被折叠的 条评论
为什么被折叠?



