zoukankan      html  css  js  c++  java
  • maximun-depth-of-binary-tree

    题目:

    Given a binary tree, find its maximum depth.

    The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

    此题类似二叉树最小深度。

    /**

     * Definition for binary tree

     * public class TreeNode {

     *     int val;

     *     TreeNode left;

     *     TreeNode right;

     *     TreeNode(int x) { val = x; }

     * }

     */

    import java.util.*;

    public class Solution {

        public int maxDepth(TreeNode root) {

            if(root==null)

                return 0;

            if(root.left==null&&root.right==null)

                return 1;

    方法一:递归

        /*    if(root.left==null)

                return maxDepth(root.right)+1;

            if(root.right==null)

                return maxDepth(root.left)+1;

            int left=maxDepth(root.left);

            int right=maxDepth(root.right);

           

            return (left>right)?(left+1):(right+1);

           

            */

            //方法二:层序遍历结束,每一层level加一

            Queue<TreeNode> q=new LinkedList<>();

            q.add(root);

            int level=0;

            while(!q.isEmpty()){

                int size=q.size();

                level++;

                for(int i=0;i<size;i++){

                    TreeNode node=q.poll();

                    if(node.left!=null)

                        q.add(node.left);

                    if(node.right!=null)

                        q.add(node.right);

                }

            }

           

            return level;

        }

    }

  • 相关阅读:
    php图片水印添加,压缩,剪切的封装类
    使用观察者模式处理异常信息
    php中的错误级别
    php 递归函数的三种实现方式
    php利用递归函数实现无限级分类
    利用http协议发布博客园博文评论
    结合php ob函数理解缓冲机制
    php 正则表达式捕获组与非捕获组
    php 利用socket发送GET,POST请求
    php mysqli扩展之预处理
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8029858.html
Copyright © 2011-2022 走看看