1:完全二叉树的节点个数
递归就是三部曲
1: 确定参数为当前节点 root 返回值为 节点数
2: 确定终止条件 就是if(root == null ) return 0
3: 确定每一层的处理 就是为左子树的节点个数加右字数的节点个数加1
迭代就是层次遍历我们可以统计
class Solution {
public int countNodes(TreeNode root) {
//因为是完全二叉树所以我们采取层次遍历
int res = 0;
Queue<TreeNode> que = new LinkedList<>();
if(root == null) return 0;
que.offer(root);
while(!que.isEmpty()){
int size = que.size();
res += size;
while(size-- >0){
TreeNode tempnode = que.poll();
if(tempnode.left != null) que.offer(tempnode.left);
if(tempnode.right != null) que.offer(tempnode.right);
}
}
return res;
}
}
2:平衡二叉树的判定
一开始的思路递归三部曲
1: 确定参数就是当前节点 root 返回结果是bollean值
2: 确定终止条件 root == null return true;
3: 对于当层的逻辑就是,我保证本节点的左子树右子树高度差不超1,并且左子树和右子树都是平衡二叉树
class Solution {
public int height(TreeNode root){
if(root == null) return 0;
int leftheight = height(root.left);
int rightheight = height(root.right);
return 1 + Math.max(leftheight, rightheight);
}
public boolean isBalanced(TreeNode root) {
int leftheight = height(root.left);
int rightheight = height(root.right);
return Math.abs(leftheight - rightheight) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
}
注意到我们其实求root的高度时我们就已经把所有节点的高度求出了,上述代码存在这重叠的求高度过程故对代码进行优化,只求一次root的高度就足够了
class Solution {
//在求root高度时判断有没有节点破坏平衡二叉树的规则
boolean flag = true;
public int height(TreeNode root){
if(root == null) return 0;
int leftheight = height(root.left);
int rightheight = height(root.right);
if(Math.abs(leftheight - rightheight) >=2 ) flag = false;
return 1 + Math.max(leftheight, rightheight);
}
public boolean isBalanced(TreeNode root) {
height(root);
return flag;
}
}