博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
maximun-depth-of-binary-tree
阅读量:4323 次
发布时间:2019-06-06

本文共 1031 字,大约阅读时间需要 3 分钟。

题目:

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;

    }

}

转载于:https://www.cnblogs.com/xiaolovewei/p/8029858.html

你可能感兴趣的文章
为django项目创建虚拟环境
查看>>
30-RoutingMiddleware介绍以及MVC引入
查看>>
【转】AB实验设计思路及实验落地
查看>>
PHP获取客户端的IP
查看>>
C# 创建单例窗体封装
查看>>
移动端报表如何获取当前地理位置
查看>>
spring 源码
查看>>
使用 opencv 将图片压缩到指定文件尺寸
查看>>
linux中~和/的区别
查看>>
在vue-cli项目中使用bootstrap的方法示例
查看>>
jmeter的元件作用域与执行顺序
查看>>
echarts学习笔记 01
查看>>
PrimeNG安装使用
查看>>
iOS 打包
查看>>
.NET Core中的数据保护组件
查看>>
华为云软件开发云:容器DevOps,原来如此简单!
查看>>
MyEclipse 快捷键(转载)
查看>>
03链栈_LinkStack--(栈与队列)
查看>>
会滚段
查看>>
MANIFEST.MF的用途(转载)
查看>>