104.二叉树的最大深度

给定一个二叉树 root ,返回其最大深度。

二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。

1
2
3
4
5
6
7
8
9
public class Solution{
public int maxDepth(TreeNode root){
return dfs(root,0);
}
private int dfs(TreeNode root,int depth){
if(root==null) return depth;
return Math.max(dfs(root.left),dfs(root.right))+1;
}
}

105.相同的树

给你两棵二叉树的根节点 pq ,编写一个函数来检验这两棵树是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

1
2
3
4
5
6
7
8
9
10
11
12
public class Solution{
public boolean isSameTree(TreeNode p, TreeNode q){
if(q==null&&p==null){
return true;
}
if(q==null&&p!=null||q!=null&&p==null){
return false;
}
if(q.val!=p.val) return false;
return isSameTree(p.left,q.left)&&isSameTress(p.right,q.right);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null){
return true;
}
if(p!=null&&q!=null){
if(q.val==p.val)
return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}
return false;
}
}