博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
算法-树-二叉树的最大深度
阅读量:3961 次
发布时间:2019-05-24

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

在这里插入图片描述

方法一 递归

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode() {} *     TreeNode(int val) { this.val = val; } *     TreeNode(int val, TreeNode left, TreeNode right) { *         this.val = val; *         this.left = left; *         this.right = right; *     } * } */class Solution {
public int maxDepth(TreeNode root) {
if(root == null) {
return 0; } //如果为空 直接返回0 int a = maxDepth(root.left); int b = maxDepth(root.right); return Math.max(a, b) + 1;//加上根节点的层数 }}

方法二 广度优先搜索

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode() {} *     TreeNode(int val) { this.val = val; } *     TreeNode(int val, TreeNode left, TreeNode right) { *         this.val = val; *         this.left = left; *         this.right = right; *     } * } */class Solution {
public int maxDepth(TreeNode root) {
if(root == null) {
return 0; } Queue
queue = new LinkedList<>(); queue.offer(root); int ans = 0; while(!queue.isEmpty()) {
//记录每一行的节点个数 一行全部从队列拿完ans就加一 int size = queue.size(); while(size > 0) {
TreeNode cur = queue.poll(); //拿出一个size-- size--; if(cur.left != null) {
queue.offer(cur.left); } if(cur.right != null) {
queue.offer(cur.right); } } //一行拿完 ans++; } return ans; }}

转载地址:http://qlhzi.baihongyu.com/

你可能感兴趣的文章
autoit3 ie.au3 函数之——_IEErrorNotify
查看>>
autoit3 ie.au3 函数之——_IEFormElementCheckBoxSelect & _IEFormGetObjByName
查看>>
autoit3 ie.au3 函数之——_IEFormElementGetCollection & _IEFormGetCollection
查看>>
watir测试报告(一)
查看>>
watir测试报告(二)
查看>>
watir——上传文件
查看>>
Python之读取TXT文件的三种方法
查看>>
Python之操作MySQL数据库
查看>>
watir学习之—如何遍历页面所有的超链接
查看>>
ruby之——安装gem提示:Please update your PATH to include build tools or download the DevKit
查看>>
Selenium-Webdriver系列教程(一)————快速开始
查看>>
Selenium-Webdriver系列教程(2)———浏览器的简单操作
查看>>
Selenium-webdriver系列教程(3)———如何执行一段js脚本
查看>>
Selenium-webdriver系列教程(4)——如何定位测试元素
查看>>
Selenium-webdriver系列教程(5)———如何定位frame中的元素
查看>>
Selenium-webdriver系列教程(6)———如何捕获弹出窗口
查看>>
Eclipse(Windowns XP)下搭建Android开发环境——简介
查看>>
Android自动化工具Monkeyrunner使用(一)
查看>>
Android自动化工具Monkeyrunner使用(二)
查看>>
Android自动化工具Monkeyrunner使用(三)
查看>>