完全二叉树的节点个数和平衡二叉树的判定

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;

    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值