二叉树的深度

此博客链接:https://www.cnblogs.com/ping2yingshi/p/14102478.html

二叉树的深度

题目链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/submissions/

题目

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

3
/
9 20
/
15 7
返回它的最大深度 3 。

题解

思路1:

        按照前面做过的前中后序遍历,可以进行层次遍历,然后判断层次遍历中有多少层,就可以计算出二叉树的深度是多少了。

思路2:

      按照前面写的,也可以利用递归来实现计算二叉树的深度,这里主要说前序遍历的递归思想,先回忆一下前序遍历递归思想,先遍历根,在遍历左子树,然后遍历右子树,然后递归遍历左子树中的左右子树,右子树中的左右子树,在计算最大深度时,在返回根节点的最大深度时,是通过取左子树和右子树中较大深度的数加1则是根节点的最大深度。

方法1:

先写上层次遍历的模板,然后计算有多少层即为二叉树的最大深度。

代码1

class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null)
        return 0;
       Queue <TreeNode> queue= new LinkedList<>();
        int count=0;
        queue.add(root);
        while(!queue.isEmpty()){
            int len=queue.size();
            while(len>0){
                TreeNode temp=queue.poll();
                if(temp.left!=null)
                     queue.add(temp.left);
                if(temp.right!=null)
                     queue.add(temp.right);
                len--;
            }
            count++;

        }
        return count;


    }
}

结果1

 

方法2:

先把树的前序遍历递归方法写上,通过修改代码,取左右子树中较大的值,并且加1作为返回结果。

代码2

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

结果2

      

原文地址:https://www.cnblogs.com/ping2yingshi/p/14102478.html