LeetCode刷题—二叉树
1、剑指Offer-27: 二叉树的镜像
1.1、题目描述
1.2、代码实现
public class Solution{
// 递归法
public TreeNode mirrorTree(TreeNode root) {
// 终止条件
if(root == null) return null;
// 处理根节点
TreeNode tempNode = root.left;
root.left = root.right;
root.right = tempNode;
// 处理左子树
mirrorTree(root.left);
// 处理右子树
mirrorTree(root.right);
return root;
}
// 借助栈的特性
public TreeNode mirrorTree1(TreeNode root) {
if(root == null) return null;
Stack<TreeNode> stack = new Stack<>();
stack.add(root);
// 遍历存放节点的stack
while(!stack.isEmpty()){
TreeNode node = stack.pop();
// 栈 : 先进后出,所以要先让左节点进去
if(node.left != null) stack.add(node.left);
if(node.right != null) stack.add(node.right);
// 左右节点交换位置
TreeNode tempNode = node.left;
node.left = node.right;
node.right = tempNode;
}
}
}
2、剑指Offer-28: 对称的二叉树
2.1、题目描述
2.2、代码实现
public class Solution{
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
return isMirror(root.left, root.right);
}
// 判断左右子树是否对称,所以传入两个node节点
public boolean isMirror(TreeNode left, TreeNode right) {
// 递归的结束条件: 两个都为null时,说明对称返回true
if(left == null && right == null) return true;
// 其中一个为null,另一个不为null时,不对称返回false
if(left == null || right == null) return false;
// 左右两个节点值不相等时,不对称返回false
if(left.val != right.val) return false;
// 对称 : 左子树的左节点 和 右子树的右节点、右子树的左节点 和 左子树的右节点
return isMirror(left.left, right.right) && isMirror(right.left, left.right);
}
}
3、剑指Offer-32: 从上到下打印二叉树 II
3.1、题目描述
3.2、代码实现
public class Solution{
// 借助队列迭代
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
// 构建一个队列,利用"先进先出"的特性
Queue<TreeNode> queue = new LinkedList<>();
if(root != null) queue.add(root);
// 遍历队列
while(!queue.isEmpty()){
List<Integer> temp = new ArrayList<>();
// 循环次数为节点数
for(int i = queue.size(); i > 0; i--){
TreeNode node = queue.poll();
temp.add(node.val);
// 循环次数是本次的节点数,添加node个数为下层的节点数
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
res.add(temp);
}
return res;
}
// 递归法
List<List<Integer>> res1 = new ArrayList<>();
public List<List<Integer>> levelOrder1(TreeNode root) {
if(root == null) return res1;
dfs(0, root);
return res1;
}
private static void dfs(int depth, TreeNode root){
// 迭代条件
if(root == null) return null;
List<Integer> temp = new ArrayList<>();
if(depth == res1.size()) res1.add(temp);
// 处理左子树
dfs(depth + 1, root.left);
// 处理右子树
dfs(depth + 1, root.right);
}
}
4、剑指 Offer-54: 二叉搜索树的第k大节点
4.1、题目描述
4.2、代码实现
public class Solution{
/*
二叉搜索树: 左节点的值小于节点的值,右节点的值大于节点的值。
前序遍历就是从小到大的顺序
前序遍历的逆序就是从大到小的顺序
*/
public int kthLargest(TreeNode root, int k) {
this.k = k;
findKthLargest(root);
return res;
}
// 记录倒数第几大的数
private int k;
// 记录最终返回结果
private int res;
private static void findKthLargest(TreeNode root){
// 递归终止条件
if(root == null) return;
// 逆序遍历
findKthLargest(root.right);
// 如果k为0时,结束递归
if(k == 0) return;
// 递归一次就是找一个大的数字
if(--k == 0) res = root.val;
findKthLargest(root.left);
}
}
= 0) return;
// 递归一次就是找一个大的数字
if(–k == 0) res = root.val;
findKthLargest(root.left);
}
}