# 二叉树

### 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. 对称二叉树

``````/**
* 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;
}
}
``````
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}