二叉树的深度

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

二叉树的深度

题目链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/

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

例如:

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

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

题解:

        思路:层次遍历二叉树,使用队列。

                 1.节点进队。

                 2.队列不为空,节点出队时,把节点的左右孩子进队列(如果存在)。

                 3. 重复1,2.

                 4.记录层数。

代码:

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

                 

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