leetcode104.二叉树的最大深度
注意:√
- 递归法很好写
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
int res = Math.max(left,right)+1;
return res;
}
leetcode111.二叉树的最小深度
注意:√
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = minDepth(root.left);
int right = minDepth(root.right);
if (root.left == null && root.right != null) {
return right + 1;
}
if (root.left != null && root.right == null) {
return left + 1;
}
return Math.min(left, right) + 1;
}
leetcode222.完全二叉树的节点个数
注意:×
- 这个不是简单的二叉树找节点
- 注意完全二叉树的使用
- 如果左边路径等于右边路径代表了这个节点下面的树是完全二叉树,可以直接不用再进行计算了
public int countNodes(TreeNode root) {
if (root == null){
return 0;
}
TreeNode left = root.left;
TreeNode right = root.right;
int leftDep = 0;
int rightDep = 0;
while (left != null){
left = left.left;
leftDep++;
}
while (right != null){
right = right.right;
rightDep++;
}
if (leftDep == rightDep){
return (2<<leftDep)-1;
}
return countNodes(root.left)+countNodes(root.right)+1;
}