点击阅读原文
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中文章