数据结构 -- 完全/平衡二叉树

1. 完全二叉树
若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。

它的深度至少是lg(N+1)。最多也不会超过lg(2N)。

a) 判断一棵树是否是完全二叉树:按层遍历

  • 如果一个结点,左右孩子都不为空,则pop该节点,将其左右孩子入队列;
  • 如果一个结点,左为空,右不为空,则该树一定不是完全二叉树;
  • 如果一个结点,左孩子不为空,右孩子为空;或者左右孩子都为空;则该节点之后的队列中的结点都为叶子节点;该树才是完全二叉树,否则就不是完全二叉树;
public static boolean isCBT(TreeNode root){
	if(root == null) return true;
	Queue<Integer> queue = new LinkedList<>();
	//叶子结点标志位,遇到了左子树非空 右子树空的节点设为true,若要为完全二叉树,则其后所有节点必须为叶子结点
	boolean isLeaf = false;
	TreeNode l = null;
	TreeNode r = null;
	queue.offer(root);
	
	while(!queue.isEmpty()){
		root = queue.poll();
		l = root.left;
		r = root.right;
		if((isLeaf && (l != null && r != null)) || (l == null && r != null))
			return false;
			
		if(l != null){
			queue.add(l);
		}
		 
		if(r != null)
			queue.add(r);
		else
			isLeaf = true;
	}
	return true;
}

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. 平衡二叉树
判断是否为二叉搜索树

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值