zoukankan      html  css  js  c++  java
  • 二叉树的深度 --剑指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;
        }
    }
  • 相关阅读:
    0626 Django模型(ORM)
    0625 Django 基础
    0530JavaScript基础2
    CentOS7.5安装cairo-dock,比mac托盘还美
    CentOS7.5安装与使用mysql-workbench
    CentOS7.6安装rime輸入法
    CentOS7.5 firefox Flash插件更新
    记一次ceph集群的严重故障
    ceph笔记(一)
    CentOS7.6打开的程序窗口居中
  • 原文地址:https://www.cnblogs.com/nlw-blog/p/12444513.html
Copyright © 2011-2022 走看看