二叉树的深度 --剑指offer

题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
 
递归算法:
public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
         return  Math.max(1+TreeDepth(root.left) ,1 + TreeDepth(root.right));
    }
}

非递归算法: 用层次遍历来解决

 牛客上看的大佬算法  

count 代表当前层已经访问过的结点数 nextcount代表正在访问的那一层的总共结点树;

当 count=nextcount的时候 说明这个层已经访问完了 

count重置为0 nextcount设置为下一层的结点树 深度depth ++;

import java.util.LinkedList;
import java.util.Queue;
public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        Queue<TreeNode> queue=new LinkedList<>();
        queue.offer(root);
        int depth=0,count=0,nextCount=1;
        while (!queue.isEmpty()){
            TreeNode node = queue.poll();
            count ++;
            if(node.left != null){
                queue.offer(node.left);
            }
            if(node.right != null) {
                queue.offer(node.right);
            }
            if(count == nextCount){
                nextCount=queue.size();
                count = 0;
                depth ++;
            }
        }
        return depth;
    }
}
原文地址:https://www.cnblogs.com/nlw-blog/p/12444513.html