Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度 [java]
来源:互联网 发布:大数据相关技术介绍 编辑:程序博客网 时间:2024/06/06 08:31
点击阅读原文
Maximum Depth of Binary Tree
递归法
复杂度
时间 O(N) 空间 O(H) 递归栈空间
思路
简单的递归。递归条件是,它的最大深度是它左子树的最大深度和右子树最大深度中较大的那个加1。基础条件是,当遇到空节点时,返回深度为0。该递归的实质是深度优先搜索。
代码
public 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; }}
Minimum Depth of Binary Tree
递归法
复杂度
时间 O(N) 空间 O(H) 递归栈空间
思路
当求最大深度时,我们只要在左右子树中取较大的就行了,然而最小深度时,如果左右子树中有一个为空会返回0,这时我们是不能算做有效深度的。所以分成了三种情况,左子树为空,右子树为空,左右子树都不为空。当然,如果左右子树都为空的话,就会返回1。
代码
public class Solution { public int minDepth(TreeNode root) { if(root == null){ return 0; } int depth = 0; if(root.left != null && root.right != null){ int left = minDepth(root.left); int right = minDepth(root.right); depth = Math.min(left, right); } else if (root.left != null){ depth = minDepth(root.left); } else if (root.right != null){ depth = minDepth(root.right); } return depth + 1; }}
广度优先搜索
复杂度
时间 O(N) 空间 O(B)
思路
递归解法本质是深度优先搜索,但因为我们是求最小深度,并不一定要遍历完全部节点。如果我们用广度优先搜索,是可以在遇到第一个叶子节点时就终止并返回当前深度的。
代码
public class Solution { public int minDepth(TreeNode root) { Queue<TreeNode> queue = new LinkedList<TreeNode>(); if(root!=null) queue.offer(root); int depth = 0; while(!queue.isEmpty()){ int size = queue.size(); depth++; for(int i = 0; i < size; i++){ TreeNode curr = queue.poll(); if(curr.left == null && curr.right == null){ return depth; } if(curr.left != null) queue.offer(curr.left); if(curr.right != null) queue.offer(curr.right); } } return depth; }}
本文参考segmentfault中文章
阅读全文
0 0
- [Java代码] [Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度
- Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度 [java]
- Minimum Depth of Binary Tree 二叉树的最小深度
- Minimum Depth of Binary Tree 二叉树的最小深度
- Minimum Depth of Binary Tree 二叉树的最小深度
- leetcode解题之Maximum/Minimum Depth of Binary Tree Java版(树的最大、最小深度)
- Maximum Depth of Binary Tree 二叉树的最大深度
- Maximum Depth of Binary Tree 二叉树的最大深度
- Maximum Depth of Binary Tree 二叉树的最大深度
- Maximum Depth of Binary Tree 二叉树的最大深度
- maximum-depth-of-binary-tree(二叉树的最大深度)
- Tree-----求树的最大深度和最小深度(104. Maximum Depth of Binary Tree 111. Minimum Depth of Binary Tree)
- LeetCode Minimum Depth of Binary Tree 最小深度二叉树
- Minimum Depth of Binary Tree 二叉树最小深度
- Leetcode Minimum Depth of Binary Tree 二叉树最小深度
- lintcode minimum-depth-of-binary-tree 二叉树最小深度
- LeetCode:minimum-depth-of-binary-tree(二叉树最小深度)
- 【LeetCode】Maximum Depth of Binary Tree (二叉树最大深度)
- 三、 乐视2017秋招<跳跃的蚂蚱>
- 容斥原理
- Yii2.0-图片上传扩展(异步加载缩略图) [扩展组件]
- jsonp跨域请求,常见的集中书写方式,及优缺点比较
- linux 网络设置基础知识整理复习(一)碰到的各种问题
- Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度 [java]
- stdarg.h头文件中va_start va_arg va_end解析
- Thread和Runnable的子类调用
- (方法)枚举2^k所有情况
- White matter hyperintensity and stroke lesion segmentation and differentiation using cnn_part2_2017
- reactwebAPP的各个页面之间的跳转以及footer相对应!
- K-D树小结
- 2017/8/8
- 动态规划 LCS 求两个序列A,B中全部的最长公共子序列