● 104.二叉树的最大深度
必须首先确定遍历方式:
求二叉树的高度:因为求高度,就好像一座大楼在你面前,你肯定是从底层往楼顶去数,所以说呢,就是从底下往上走,那么只有后序遍历符合这个要求了,先左,再右,最后在中。
求二叉树的深度:你现在求深度,就好像你看一口井有多深,肯定是,从地面慢慢看到最深处,所以说呢,只有前序遍历符合该要求,先中,再左,再右。
一开始空结点返回值我写成1了。错了,现在直到应该是0了,还有left和right,每调用一次,就要+1,刚做这道题的时候我确实有点懵。这题因为是求最大深度,相当于高度,所以就用后序了。
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;空结点的高度是0,返回0
}
int left = 1+maxDepth(root.left);
int right = 1+maxDepth(root.right);
return Math.max(left,right);
}
}
559.n叉树的最大深度
没想明白,之后复习再看,
可能是每次运行,int depth=0只运行一次吧。
自己画一下图,你会发现,depth往往会出现再max函数里面,而且被比下去,因为在该层递归,它一直是0。
class Solution {
public int maxDepth(Node root) {
if(root == null){
return 0;
}
int depth = 0;
if(root.children != null){
for(Node child:root.children){
depth = Math.max(depth, maxDepth(child));
}
}
return depth+1;
}
}
● 111.二叉树的最小深度
是在求二叉树的最大深度的基础上,加了额外的限定条件。
class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
int left = minDepth(root.left);
int right = minDepth(root.right);
if(root.left==null){
return 1+right;
}
if(root.right==null){
return 1+left;
}
return Math.min(left,right)+1;
}
}
● 222.完全二叉树的节点个数
普通二叉树写法
class Solution {
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}
int left = countNodes(root.left);
int right = countNodes(root.right);
int count = left+right+1;
return count;
}
}
这是完全二叉树的写法,没太明白
class Solution {
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}
TreeNode left = root.left;
TreeNode right = root.right;
int leftdepth = 0, rightdepth = 0;
while(left!=null){
left = left.left;
leftdepth++;
}
while(right!=null){
right = right.right;
rightdepth++;
}
if(leftdepth==rightdepth){
return (2<<leftdepth)-1;
}
int leftnum= countNodes(root.left);
int rightnum = countNodes(root.right);
return leftnum+rightnum+1;
}
}