• Leetcode 剑指Offer 55 -I 二叉树的深度


    题目定义:

    输入一棵二叉树的根节点,求该树的深度。
    从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
    
    例如:
    
    给定二叉树 [3,9,20,null,null,15,7],
    
        3
       / 
      9  20
        /  
       15   7
    返回它的最大深度 3 。
    
     
    提示:
    
    节点总数 <= 10000
    
    

    递归方式:

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

    迭代方式:

    class Solution {
        public int maxDepth(TreeNode root) {
            if(root == null)
                return 0;
            int depth = 0;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            //可修改为 Queue<TreeNode> queue = new LinkedList<TreeNode>() {{ offer(root); }};
            //更加简洁
            while(queue.size() > 0){
                ++ depth;
                int size = queue.size();
                for(int i = 0 ;i < size; i++){
                    TreeNode node = queue.poll();
                    if(node.left != null)
                        queue.offer(node.left);
                    if(node.right != null)
                        queue.offer(node.right);
                }
            }
            return depth;
        }
    }
    

    参考:

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

  • 相关阅读:
    13.sqoop的安装
    12.Flume的安装
    11.把文本文件的数据导入到Hive表中
    10.hive安装
    9.centos7 安装mysql
    8.时间同步
    7.编写mapreduce案例
    mysql中如何处理字符
    装箱拆箱隐含的问题
    何谓幂等性
  • 原文地址:https://www.cnblogs.com/CodingXu-jie/p/14148700.html
Copyright © 2020-2023  润新知