39 二叉树的深度(层次遍历)

本文介绍了如何计算二叉树的深度,提供了递归和层次遍历两种方法。递归方法中,当根节点为空时返回0,否则返回孩子节点深度加1。层次遍历则利用广度优先搜索实现,避免了递归可能导致的栈溢出风险。两种方法的时间复杂度分别为O(lgN)和O(N)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

public class Solution {
    public int TreeDepth(TreeNode root) {
        int leftDepth = 0;
        int rightDepth = 0;
        if(root == null)
            return 0;
        if(root.left==null && root.right==null)
            return 1;
        if(root.left != null){
             leftDepth = TreeDepth(root.left) + 1;
        }
        if(root.right != null){
             rightDepth = TreeDepth(root.right) + 1;
        }
        return (rightDepth > leftDepth) ? rightDepth : leftDepth;
    }
}

使用递归的方法,当root为null时,返回0;当root左右孩子都为null时,返回1;

更简化一点:

public class Solution {
    public int TreeDepth(TreeNode root) {
        int leftDepth = 0;
        int rightDepth = 0;
        if(root == null)
            return 0;
        leftDepth = TreeDepth(root.left) + 1;
        rightDepth = TreeDepth(root.right) + 1;

        return (rightDepth > leftDepth) ? rightDepth : leftDepth;
    }
}

root为null时,返回0;不为null时,返回它的孩子长度+1;

import java.util.*;
public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root == null)
            return 0;
        Queue<TreeNode> queue = new LinkedList();
        TreeNode nlast = null;
        TreeNode last = root;
        int level = 0;
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if(cur.left != null){
                queue.offer(cur.left);
                nlast = cur.left;
            }
            if(cur.right != null){
                queue.offer(cur.right);
                nlast = cur.right;
            }
            if(cur == last){
                level++;
                last = nlast;
            }
        }
        return level;
    }
}

注意:让last指向当前行的最后一个元素,nlast指向下一行的最后一个 元素,当当前元素cur和last相同的时候,说明当前行已经遍历到了最后一个,它的左右孩子也已经入队了,nlast也指向了下一行的最后一个元素,这时候让last指向nlast即可!

https://blog.youkuaiyun.com/xuchonghao/article/details/79405611

https://blog.youkuaiyun.com/Zheng548/article/details/65935030中有句话很好:求二叉树的深度,有:
1. 递归,这也是很多人非常容易想到的,递归实际也是深度优先的思想(DFS),时间复杂度为O(lgN),但是空间复杂度最坏为O(N),当二叉树退化为链表的时候。
2. 循环,这种方法不会有递归方法容易出现的栈溢出风险。循环其实是广度优先的思想(BFS)。时间复杂度O(N)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值