104.二叉树的最大深度
使用变量和目前已知的深度进行比较,并使用max函数进行更新
// recursion
private int d = 0;
public int maxDepth(TreeNode root) {
if (root == null) return 0;
dfs(root, 1);
return d;
}
private void dfs(TreeNode root, int h){
if (root.left == null && root.right == null){
d = Math.max(d, h);
}
if (root.left != null) dfs(root.left, h + 1);
if (root.right != null) dfs(root.right, h + 1);
}
// uniform iteration
public int maxDepth(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
int res = 1;
queue.offer(root);
queue.offer(null);
while(queue.peek() != null){
while(queue.peek() != null){
TreeNode node = queue.poll();
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
queue.offer(null);
queue.poll();
if (queue.peek() != null) res++;
}
return res;
}
111.二叉树的最小深度
思路为判断左右节点是否有null
如果有则只看另外一边子树的高度
否则同时判断两个子树的高度,并且在每次递归后取较小值
public int minDepth(TreeNode root) {
if (root == null) return 0;
if (root.left == null) return minDepth(root.right) + 1;
if (root.right == null) return minDepth(root.left) + 1;
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
222.完全二叉树的节点个数
简单递归写法,使用所有二叉树,复杂度为O(n),不满足附加要求
int res = 1;
public int countNodes(TreeNode root) {
if (root == null) return 0;
dfs(root);
return res;
}
private void dfs(TreeNode root){
if (root.left == null && root.right == null) return ;
if (root.left != null){
res++;
dfs(root.left);
}
if (root.right != null){
res++;
dfs(root.right);
}
}
使用完全二叉树性质:
比较一个节点两边子树的高度
如果相同则说明左子树为完全二叉树(套用公式计算此子树的总节点数)
否则右子树为完全二叉树(套用公式计算此子树的总节点数)
代码书写注意点:
- 使用<<降低幂运算时间
- 需要使用括号 (1 << left) 和 (1 << right) 纠正运算顺序,否则默认先执行加法,再位运算
public int countNodes(TreeNode root) {
if (root == null) return 0;
int left = getDepth(root.left);
int right = getDepth(root.right);
if (left == right) return (1 << left) + countNodes(root.right);
else return (1 << right) + countNodes(root.left);
}
private int getDepth(TreeNode root){
int d = 0;
while(root != null){
root = root.left;
d++;
}
return d;
}
此方法复杂度为O((log n)^2)