剑指offer- 二叉树的深度

二叉树的深度

题目描述:

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

题目思路:

树的遍历方式分为两种:深度优先遍历(DFS),广度优先遍历(BFS)

方法一:深度优先,后序遍历

树的深度等于左子树深度和右子树深度最大值加1

class Solution1 {
    
    
    public int maxDepth(TreeNode root) {
    
    
        if(root == null){
    
    
            return 0;
        }
        return Math.max(maxDepth(root.left), maxDepth(root.right)) +;
    }
}

方法二: 层序遍历,BFS

往往采用队列来实现

特列处理: 当root 为空时,直接返回0

初始化: 把root加入queue 计数器res= 0

循环遍历:当queue为空时跳出

  1. 初始化一个空列表tmp 用来存储下一层节点
  2. 遍历队列:遍历各节点,并将左子节点和右子节点加入tmp
  3. 更新队列:执行queue=tmp ,将下一层节点赋值给queue
  4. 统计层数:执行res+=1

返回res

class Solution1{
    
    
    public int maxDepth(TreeNode root){
    
    
        if(root == null) {
    
    
            return 0;
        }
        List<TreeNode> queue = new LinkedList<>(),tmp;
        // 将根节点加入队列
        queue.add(root);
        int res = 0;
        // 当队列不为空,循环遍历层级节点
        while(!queue.isEmpty()){
    
    
            tmp = new LinkedList<>();
            for (TreeNode treeNode : queue) {
    
    
                if(treeNode.left != null){
    
    
                    tmp.add(treeNode.left);
                }
                if(treeNode.right != null){
    
    
                    tmp.add(treeNode.right);
                }
            }

            queue = tmp;
            res++;
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_31702655/article/details/114905623