Day16 二叉树part03
我的思路:
递归,最后注意是1 + max(left, right)
解答:
class Solution {
public int maxDepth(TreeNode root) {
return getMaxDepth(root);
}
public int getMaxDepth(TreeNode root) {
if(root == null) {
return 0;
}
int left = getMaxDepth(root.left);
int right = getMaxDepth(root.right);
int max_Depth = Math.max(left, right) + 1;
return max_Depth;
}
}
我的思路:
列举出左右子树为空的特殊情况后,递归返回1 + min(left, right)
解答:
class Solution {
public int minDepth(TreeNode root) {
return getMinDepth(root);
}
public int getMinDepth(TreeNode root) {
if(root == null) {
return 0;
}
int left = getMinDepth(root.left);
int right = getMinDepth(root.right);
if(root.left == null && root.right != null) {
return 1 + right;
}
if(root.left != null && root.right == null) {
return 1 + left;
}
int min_Depth = 1 + Math.min(left, right);
return min_Depth;
}
}
我的思路:
完全二叉树结点 = left + right + 1
解答:
class Solution {
public int countNodes(TreeNode root) {
return getNodes(root);
}
public int getNodes(TreeNode root) {
if(root == null) {
return 0;
}
int left = getNodes(root.left);
int right = getNodes(root.right);
int all = left + right + 1;
return all;
}
}