day14:二叉树part3,高度/深度,完全二叉树节点个数
559.N 叉树的最大深度
class Solution {
public int maxDepth(Node root) {
// 空节点
if (root == null) return 0;
// 叶子节点
List<Node> children = root.children;
if (children.size() == 0) return 1;
// 有孩子的节点
int max = Integer.MIN_VALUE;
for (Node child : children) {
int depth = maxDepth(child);
if (depth > max)
max = depth;
}
return max + 1;
}
}
111.二叉树的最小深度
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
// 左右孩子都不为空
else if (root.left != null && root.right != null)
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
// 左右孩子中有空,需要算非空孩子的深度,空节点返回0,加上不影响
// 把左右孩子其中一个为空 和 两个都为空(叶子节点return 1) 合并了
else return minDepth(root.left) + minDepth(root.right) + 1;
}
}
迭代法待更新
222.完全二叉树的节点个数
当作普通二叉树来处理
其实是后序遍历的思路
class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
利用完全二叉树性质:
- 完全二叉树分别递归左孩子,和右孩子,递归到某一深度一定会有左孩子或者右孩子为满二叉树,然后可以利用满二叉树公式计算节点个数
- 递归向左遍历的深度等于递归向右遍历的深度,可以判断是否是满二叉树
class Solution {
/**
* 针对完全二叉树的解法
*
* 满二叉树的结点数为:2^depth - 1
*/
public int countNodes(TreeNode root) {
return count(root);
}
public int count(TreeNode root) {
if (root == null) return 0;
TreeNode left = root.left;
TreeNode right = root.right;
// 初始为 0 为了下面计算公式方便
int leftDepth = 0, rightDepth = 0;
while (left != null) {
left = left.left;
leftDepth++;
}
while (right != null) {
right = right.right;
rightDepth++;
}
if (leftDepth == rightDepth)
// (2 << 1) 相当于2^2,所以leftDepth初始为0
return (2 << leftDepth) - 1;
return count(root.left) + count(root.right) + 1;
}
}