zoukankan      html  css  js  c++  java
  • 104. Maximum Depth of Binary Tree

    一、题目

      1、审题

      2、分析

        给出一棵二叉树,输出其最大深度。

    二、解答

      1、思路:

        方法一、

          采用递归方式,输出其最大深度。

    public int maxDepth(TreeNode root) {
            return getDepthHelper(root, 1);
        }
        
        
        private int getDepthHelper(TreeNode root, int depth) {
            
            if(root == null)
                return depth - 1;
            
            return Math.max(getDepthHelper(root.left, depth + 1), getDepthHelper(root.right, depth + 1));
        }

      

      方法二、

        直接在此方法上递归。

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

      方法三、

        采用 BFS 广度优先遍历,用一变量记录深度。

    public int maxDepth2(TreeNode root) {
            
            if(root == null)
                return 0;
            int depth = 0;
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            
            while(!queue.isEmpty()) {
                depth++;
                int size = queue.size();
                while(size-- > 0) {
                    if(queue.peek().left != null)
                        queue.add(queue.peek().left);
                    if(queue.peek().right != null)
                        queue.add(queue.peek().right);
                    queue.poll();
                }
            }
            
            return depth;
        }

      方法四、

        利用 DFS 深度优先遍历方法;

        采用两个栈,一个栈记录节点,另一个栈记录节点对应的深度,也采用一个变量记录最大深度。

    public int maxDepth4(TreeNode root) {
            
            if(root == null)
                return 0;
            int max = 0;
            Stack<TreeNode> stack = new Stack<>();
            Stack<Integer> value = new Stack<>();
            stack.push(root);
            value.push(1);
            while(!stack.isEmpty()) {
                TreeNode node = stack.pop();
                int tmp = value.pop();
                
                max = Math.max(tmp, max);
                
                if(node.left != null) {
                    stack.push(node.left);
                    value.push(tmp+1);
                }
                if(node.right != null) {
                    stack.push(node.right);
                    value.push(tmp+1);
                }
            }
            
            return max;
        }
  • 相关阅读:
    解决Django在mariadb创建的表插入中文乱码的问题
    运行在CentOS7.5上的Django项目时间不正确问题
    获取百度网盘真实下载连接
    Django2.x版本在生成数据库表初始化文件报错
    Pycharm中的Django项目连接mysql数据库
    Django2.x版本路由系统的正则写法以及视图函数的返回问题
    CentOS7.5安装坚果云
    CentOS7.5安装下载工具
    CentOS6.5修改/etc/pam.d/sshd后root无法ssh登陆
    oracle 时间
  • 原文地址:https://www.cnblogs.com/skillking/p/9733218.html
Copyright © 2011-2022 走看看