zoukankan      html  css  js  c++  java
  • 剑指 Offer 55

    思路:

    统计层数,一开始想能不能dfs做,但怎么想感觉都不好做(脑袋里还是遍历的想法),然后自然就想到层序遍历,然后每次经过一层加一就行

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

    接着看到了递归写法

    其实用递归思考这道题目不需要想这是什么遍历(其实是后序),逻辑已经足够清晰了:

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

    这两个的时间复杂度应该是一样的,不知道为什么迭代出来时间会长一些

  • 相关阅读:
    第六次学习笔记
    第四篇笔记
    第三篇学习笔记
    第二篇学习笔记
    第一篇学习笔记
    px与dp、sp之间的转换
    SQLite的使用(二):数据增删改查
    Logcat的级别以及Logcat的调试使用
    Android 创建服务(一)
    简说SQLite
  • 原文地址:https://www.cnblogs.com/take-it-easy/p/14367913.html
Copyright © 2011-2022 走看看