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;
}
}

剑指 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);
}
}
网友评论