Offer 27. 二叉树的镜像
题目
比较简单,先保存左子树 ,翻转右子树到左子树位置,再次翻转左子树到右子树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if (root == null) return null;
TreeNode tmp = root.left;
root.left = mirrorTree(root.right);
root.right = mirrorTree(tmp);
return root;
}
}
Offer 28. 对称二叉树
对称二叉树
要注意当左右都是null时,也是对称的
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return root == null ? true : isSubSymmetric(root.left,root.right);
}
public boolean isSubSymmetric(TreeNode left, TreeNode right) {
if(left == null && right == null) return true;
if(left == null || right == null || left.val != right.val) return false;
return isSubSymmetric(left.left,right.right) && isSubSymmetric(left.right,right.left);
}
}
Offer 68 - II. 二叉树的最近公共祖先
二叉树的最近公共祖先
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
/**
* 去以root为根节点的二叉树中查找p、q的最近公共祖先
* ① 如果p、q同时存在于这棵二叉树中,就能成功返回它们的最近公共祖先
* ② 如果p、q都不存在于这棵二叉树中,返回null
* ③ 如果只有p存在于这棵二叉树中,返回p
* ④ 如果只有q存在于这棵二叉树中,返回q
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if(left != null && right != null) return root;
return left != null ? left : right;
}
}
截屏2022-06-30 18.41.03.png
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
二叉搜索树,就是右子树永远都大于左子树
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if ((root.val - p.val) * (root.val - q.val) <= 0) {
return root;
}
return lowestCommonAncestor(p.val > root.val ? root.right : root.left, p, q);
}
}
面试题34. 二叉树中和为某一值的路径
参考: https://leetcode.cn/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/solution/mian-shi-ti-34-er-cha-shu-zhong-he-wei-mou-yi-zh-5/
解题思路是前序遍历 + 路径记录
重点和难点在于理解 path.removeLast();
, 是为了回溯。
class Solution {
LinkedList<List<Integer>> res = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
recur(root, sum);
return res;
}
void recur(TreeNode root, int tar) {
if(root == null) return;
path.add(root.val);
tar -= root.val;
if(tar == 0 && root.left == null && root.right == null)
res.add(new LinkedList(path));
recur(root.left, tar);
recur(root.right, tar);
path.removeLast();
}
}