LeetCode—111. Minimum Depth of Binary Tree & 104. Maximum Depth of Binary Tree
题目
https://leetcode.com/problems/minimum-depth-of-binary-tree/description/
https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
二叉树的最小深度。 以及最大深度
思路及解法
递归
这道题其实需要想明白有哪几种情况:
- 父节点为空,深度是0
- 父节点不为空时,最小深度不一定就是两棵树中较小的深度,有可能一棵树是空的,这时候最小深度就是另一棵树的深度+1
- 若是两棵子树都不为空,返回较小的深度
- 若是其中任意一颗为空,返回另一颗(不管这颗是否是空)的深度+1
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root!=null && root.left!=null && root.right!=null){
int l = minDepth(root.left);
int r = minDepth(root.right);
return (l<r?l:r)+1;
}else if(root!=null && root.left==null){
return 1+minDepth(root.right);
}else if (root!=null && root.right==null){
return 1+minDepth(root.left);
}else{
return 0;
}
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root!=null && root.left!=null && root.right!=null){
int l = maxDepth(root.left);
int r = maxDepth(root.right);
return (l>r?l:r)+1;
}else if(root!=null && root.left==null){
return 1+maxDepth(root.right);
}else if(root!=null && root.right==null){
return 1+maxDepth(root.left);
}else{
return 0;
}
}
}