1. 完全二叉树
若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。
它的深度至少是lg(N+1)。最多也不会超过lg(2N)。
a) 判断一棵树是否是完全二叉树:按层遍历
- 如果一个结点,左右孩子都不为空,则pop该节点,将其左右孩子入队列;
- 如果一个结点,左为空,右不为空,则该树一定不是完全二叉树;
- 如果遇到一个结点,左孩子不为空,右孩子为空;或者左右孩子都为空;则该节点之后的队列中的结点都为叶子节点;该树才是完全二叉树,否则就不是完全二叉树;
b) 求完全二叉树的节点个数,复杂度低于0(n)
对于满二叉树,高度n,节点为2^n - 1,一个节点右子树的左边界到达最后一层,则其左边界是满的;若没到,则右子树是少一层的满二叉树。
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}
int left = countLevel(root.left);
int right = countLevel(root.right);
if(left == right){
return countNodes(root.right) + (1<<left);
}else{
return countNodes(root.left) + (1<<right);
}
}
private int countLevel(TreeNode root){
int level = 0;
while(root != null){
level++;
root = root.left;
}
return level;
}
2. 平衡二叉树
最小二叉平衡树的节点的公式如下 F(n)=F(n-1)+F(n-2)+1, 这个类似于一个递归的数列,可以参考Fibonacci数列,1是根节点,F(n-1)是左子树的节点数量,F(n-2)是右子树的节点数量。
boolean isBalance = true;
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
height(root);
return isBalance;
}
private int height(TreeNode root){
if(root == null) return 0;
int left = height(root.left);
int right = height(root.right);
if(Math.abs(left - right) > 1){
isBalance = false;
}
return Math.max(left, right) + 1;
}
3 最近公共祖先
3.1 普通二叉树
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
if (root == p) {
return p;
}
if (root == q) {
return q;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) {
return root;
}
return left == null ? right : left;
}
3.2 二叉搜索树
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
int val = root.val;
if (val > p.val && val > q.val) {
return lowestCommonAncestor(root.left, p, q);
}
if (val < p.val && val < q.val) {
return lowestCommonAncestor(root.right, p, q);
}
return root;
}