20230926刷题记录
参考代码随想录来刷的。
关键词:二叉树
1 226.翻转二叉树
力扣题目链接
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
递归
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null)
return;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
迭代
class Solution {
public TreeNode invertTree(TreeNode root) {
ArrayDeque<TreeNode> stack = new ArrayDeque<>();
TreeNode p = root;
TreeNode lastVisit = null;
while (p != null || !stack.isEmpty()) {
if (p == null) {
p = stack.peek();
if (p.right != null && lastVisit != p.right) {
p = p.right;
} else {
// visit
p = stack.pop();
TreeNode temp = p.left;
p.left = p.right;
p.right = temp;
lastVisit = p;
p = null;
}
} else {
stack.push(p);
p = p.left;
}
}
return root;
}
}
2 101. 对称二叉树
力扣题目链接
给你一个二叉树的根节点 root , 检查它是否轴对称。
class Solution {
public boolean isSymmetric(TreeNode root) {
return recursion(root.left, root.right);
}
private boolean recursion(TreeNode left, TreeNode right) {
if (left == null && right == null)
return true;
if (left == null || right == null)
return false;
if (left.val != right.val)
return false;
return recursion(left.left, right.right) && recursion(left.right, right.left);
}
}
3 222.完全二叉树的节点个数
力扣题目链接
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
对于普通二叉树,获取结点个数的方法是遍历所有结点,时间复杂度为O(n)。
代码如下
class Solution {
public int countNodes(TreeNode root) {
int[] res = {0};
recursion(root, res);
return res[0];
}
private void recursion(TreeNode root, int[] res) {
if (root == null)
return;
res[0]++;
recursion(root.left, res);
recursion(root.right, res);
}
}
对于高度为 h 的满二叉树,结点个数为
2
h
−
1.
2^h-1.
2h−1.
对于完全二叉树,可以拆为多个满二叉树。
如何判断一个完全二叉树是不是满二叉树?
如果向左遍历和向右遍历的深度相等,则是;否则,则不是。
这里向左遍历、向右遍历即不用遍历全部结点。
class Solution {
public int countNodes(TreeNode root) {
if (root == null)
return 0;
TreeNode left = root.left;
TreeNode right = root.right;
int leftDepth = 0;
int rightDepth = 0;
while (left != null) {
left = left.left;
leftDepth++;
}
while (right != null) {
right = right.right;
rightDepth++;
}
if (leftDepth == rightDepth)
// 2 << leftDepth 表示 2的leftDepth+1次方
return (2 << leftDepth) - 1;
return countNodes(root.left) + countNodes(root.right) + 1;
}
}