257. 二叉树的所有路径
看的答案
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res=new LinkedList<>();
if(root==null) return res;
List<Integer> path=new LinkedList<>();
return traversal(root,path,res);
}
public List<String> traversal(TreeNode root,List path,List res){
path.add(root.val);
if(root.left==null&&root.right==null){
StringBuilder str=new StringBuilder();
for(int i=0;i<path.size()-1;i++){
str.append(path.get(i));
str.append("->");
}
str.append(path.get(path.size()-1));//这里的path.size()-1要在get方法中
res.add(str.toString());//要用toString方法,因为res中元素的类型是String,而我们创建的是StringBuilder
}
if(root.left!=null){
traversal(root.left,path,res);
path.remove(path.size()-1);
}
if(root.right!=null){
traversal(root.right,path,res);
path.remove(path.size()-1);
}
return res;//要写在所有if外面,否则编译不通过
}
}
1、首先是StringBuilder的方法和List的方法之间的不同:
①StringBuilder的常用方法有:append、delete、setCharAt、charAt、insert、遍历、toString、length
②List常用方法有:add、remove、set、get、遍历、size
2、为啥不用String而是StringBuilder,因为StringBuilder更快,效率高
100.判断两棵树是否相同
人家自己写的!真棒棒!
public boolean isSame(TreeNode p,TreeNode q){
if(p==null&&q==null)return true;
if(p==null||q==null||p.val!=q.val)return false;
return isSame(p.left,q.left)&&isSame(p.right,q.right);
}
572.另一棵树的子树
人家自己写的!真棒棒!
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if(root==null&&subRoot==null)return true;
if(root==null||subRoot==null)return false;
if(root.val==subRoot.val&&isSame(root,subRoot))return true;
return isSubtree(root.left,subRoot)||isSubtree(root.right,subRoot);
}
public boolean isSame(TreeNode p,TreeNode q){
if(p==null&&q==null)return true;
if(p==null||q==null||p.val!=q.val)return false;
return isSame(p.left,q.left)&&isSame(p.right,q.right);
}
}
404. 左叶子之和
看的答案
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
Stack<TreeNode> stack=new Stack<>();
if(root==null) return 0;
stack.push(root);
int val=0;
while(!stack.isEmpty()){
TreeNode cur=stack.pop();
if(cur.left!=null&&cur.left.left==null&&cur.left.right==null){
val+=cur.left.val;
}
if(cur.right!=null)stack.push(cur.right);
if(cur.left!=null)stack.push(cur.left);
}
return val;
}
}