《剑指 Offer》学习(4)—— 55_二叉树的深度、判断是否为平衡二叉树

1 计算二叉树深度

非递归实现

public int nonRecursive(TreeNode root){
    if(root == null)
        return 0;
    Queue<TreeNode> queue = new ArrayList<>();
    queue.add(root);
    int depth = 0, count = 0, nextLayerCount = 1;
    while (queue.size() != 0){
        TreeNode top = queue.poll();
        count ++;
        if(top.left != null)
            queue.add(top.left);
        if(top.right != null)
            queue.add(top.right);
        if(count == nextLayerCount){
            nextLayerCount = queue.size();
            count = 0;
            depth++;
        }
    }
    return depth;
}

递归实现

public int recursive(TreeNode node){
    if(root == null)
        return 0;
    int leftDepth = recursive(root.left);
    int rightDepth = recursiove(root.right);
    return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}

完整版:

public class TreeDepth {
    public int NonRecursive(TreeNode root) {
        if (root == null)
            return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        // depth 当前节点所在层数
        // count 在当前层已经遍历的节点数
        // nextCount 下层节点的数量
        int depth = 0, count = 0, nextCount = 1;
        // 队列非空
        while (queue.size() != 0) {
            // 取出队首节点
            TreeNode top = queue.poll();
            count++;
            if (top.left != null)
                queue.add(top.left);
            if (top.right != null)
                queue.add(top.right);
            // 本层节点遍历结束
            if (count == nextCount) {
                nextCount = queue.size();
                count = 0;
                depth++;
            }
        }
        return depth;
    }

    public int Recursive(TreeNode root) {
        if (root == null)
            return 0;
        int left = Recursive(root.left);
        int right = Recursive(root.right);
        return left > right ? left + 1 : right + 1;
    }
}

2 判断是否为平衡二叉树

public boolean isBalanced = true;
public boolean isBalancedTree(TreeNode root){
    getDepth(root);
    return isBalanced;
}
public int getDepth(TreeNode node){
    if ( node == null ){
        return 0;
    int left = getDepth(node.left);
    int right = getDepth(node.right);
    if(Math.abs(left - right) > 1){
        isBalanced = false;
        return 0;
    }
    return left > right : left + 1 : right + 1 ;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值