剑指-简单-二叉树的深度

题目描述

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

思路

后序遍历(DFS) 和 层序遍历(BFS) 两种解法。

代码

一、递归(DFS)/ 后序
树的深度和其左(右)子树的深度之间的关系。显然,此树的深度 等于 左子树的深度 与 右子树的深度 中的 最大值 +1 。

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

二、层序遍历(BFS):利用 队列 实现。
每遍历一层,则计数器 +1,直到遍历完成,则可得到树的深度。

class Solution {
    
    
    public int maxDepth(TreeNode root) {
    
    
        if(root == null) return 0;
        List<TreeNode> queue = new LinkedList<>() {
    
    {
    
     add(root); }}, tmp;
        int res = 0;
        while(!queue.isEmpty()) {
    
    
            tmp = new LinkedList<>();
            for(TreeNode node : queue) {
    
    
                if(node.left != null) tmp.add(node.left);
                if(node.right != null) tmp.add(node.right);
            }
            queue = tmp;
            res++;
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_32301683/article/details/108362570