代码随想录算法训练营第十六天 | 二叉树 (3)

这篇博客介绍了如何计算二叉树的最大深度、最小深度以及完全二叉树的节点个数。提供了两种不同的计算方法:递归和广度优先搜索。对于最大深度和最小深度,主要通过遍历树的结构来确定;而对于完全二叉树的节点数,利用了二叉树的特性来优化计算,复杂度为O(logn)^2。
摘要由CSDN通过智能技术生成

104.二叉树的最大深度

使用变量和目前已知的深度进行比较,并使用max函数进行更新

// recursion
private int d = 0;

public int maxDepth(TreeNode root) {
    if (root == null) return 0;
    dfs(root, 1);
    return d;
}

private void dfs(TreeNode root, int h){
    if (root.left == null && root.right == null){
        d = Math.max(d, h);
    }
    if (root.left != null) dfs(root.left, h + 1);
    if (root.right != null) dfs(root.right, h + 1);
}

// uniform iteration
public int maxDepth(TreeNode root) {
    if (root == null) return 0;
    Queue<TreeNode> queue = new LinkedList<>();
    int res = 1;
    queue.offer(root);
    queue.offer(null);
    while(queue.peek() != null){
        while(queue.peek() != null){
            TreeNode node = queue.poll();
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
        }
        queue.offer(null);
        queue.poll();
    if (queue.peek() != null) res++;
    }
    return res;
}

111.二叉树的最小深度

思路为判断左右节点是否有null

如果有则只看另外一边子树的高度

否则同时判断两个子树的高度,并且在每次递归后取较小值

    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null) return minDepth(root.right) + 1;
        if (root.right == null) return minDepth(root.left) + 1;
        return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
    }

222.完全二叉树的节点个数

简单递归写法,使用所有二叉树,复杂度为O(n),不满足附加要求

int res = 1; 

public int countNodes(TreeNode root) {
    if (root == null) return 0;
    dfs(root);
    return res;
}

private void dfs(TreeNode root){
    if (root.left == null && root.right == null) return ;
    if (root.left != null){
        res++;
        dfs(root.left);
    }
    if (root.right != null){
        res++;
        dfs(root.right);
    }
}

使用完全二叉树性质:

比较一个节点两边子树的高度

如果相同则说明左子树为完全二叉树(套用公式计算此子树的总节点数)

否则右子树为完全二叉树(套用公式计算此子树的总节点数)

代码书写注意点:

  • 使用<<降低幂运算时间
  •  需要使用括号 (1 << left) 和 (1 << right) 纠正运算顺序,否则默认先执行加法,再位运算
public int countNodes(TreeNode root) {
    if (root == null) return 0;
    int left = getDepth(root.left);
    int right = getDepth(root.right);
    if (left == right) return (1 << left) + countNodes(root.right);
    else return (1 << right) + countNodes(root.left);
}

private int getDepth(TreeNode root){
    int d = 0;
    while(root != null){
        root = root.left;
        d++;
    }
    return d;
}

此方法复杂度为O((log n)^2)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值