Leetcode 104:
https://leetcode.com/problems/maximum-depth-of-binary-tree/
题目的第一想法:
这道题的解法其实很容易,就是只要看最大值就好。所以用1+max(left,right)就好。
class Solution {
public int maxDepth(TreeNode root) {
return root != null ? 1 + Math.max(maxDepth(root.left), maxDepth(root.right)): 0;
}
}
Leetcode 111:
https://leetcode.com/problems/minimum-depth-of-binary-tree/
题目的第一想法:
这道题的解法和上一道求最深node的题看似一样但需要考虑更深一层。考虑一个只有一边的node,如果只求最小值那么算法必然会走到null(因为null总为0)然后返回。如此算法就会在树的中间停止,不会返回正确答案。所以我们需要做的是把情况再次细分,有两个base case和三个recurssive condition。两个base case为当node是leaf或当node为null。三个reucrssive condition是当node左边存在branch右边不存在(往左继续计算),当node右边存在左边不存在(往右继续计算)和当node左右两边都存在(取最小值)。
class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
if(isLeaf(root)){return 1;}
else if(root.left == null && root.right != null){
return 1 + minDepth(root.right);
}else if(root.right == null && root.left != null){
return 1 + minDepth(root.left);
}else{
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
}
public boolean isLeaf(TreeNode root){
return root.left == null && root.right == null;
}
}
Leetcode 222:
https://leetcode.com/problems/count-complete-tree-nodes/description/
题目的第一想法:
这道题从难度上来看感觉不够medium的难度。基本的思路是如果是一个leaf就算1,如果是null就是0,如果是任意其他情况就recurrsion下去,关系是1+左边的数字和右边的数字。
class Solution {
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}else if(root.left == null && root.right == null){
return 1;
}else{
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
}