数据结构 -- 二叉树

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值