脚本宝典收集整理的这篇文章主要介绍了#104. 二叉树的最大深度,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:给定二叉树 [3,9,20,null,null,15,7],
3 / 9 20 / 15 7
返回它的最大深度 3 。
方法一:递归返回值为各个节点的最大路径长度class Solution { public int maxDepth(TreeNode root) { if(root==null)return 0; int left=maxDepth(root.left); int right=maxDepth(root.right); return Math.max(left,right)+1; } }
方法二:广度优先搜索 class Solution { public int maxDepth(TreeNode root) { if (root == null) { return 0; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); int ans = 0; while (!queue.iSEMpty()) { int size = queue.size(); while (size > 0) { TreeNode node = queue.poll(); if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } size--; } ans++; } return ans; } }
知识点:
Math.max(a,b) 判断a与b间最大值
总结:
无
以上是脚本宝典为你收集整理的#104. 二叉树的最大深度全部内容,希望文章能够帮你解决#104. 二叉树的最大深度所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。