# leetcode100.相同的树，101对称二叉树

## 相同的树

#### 思路一：序列化

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
String pStr = serializeTreeByPreOrder(p);
String qStr = serializeTreeByPreOrder(q);
return pStr.equals(qStr);
}

private static String serializeTreeByPreOrder(TreeNode root){
if(root == null){
return "#_";
}
String res = root.val + "_";
res += serializeTreeByPreOrder(root.left);
res += serializeTreeByPreOrder(root.right);
return res;
}
}
``````

#### 思路二：recursion

1. 判断两个指针当前节点值是否相等
2. 判断 A 的左子树与 B 的左子树是否相等
3. 判断 A 的右子树与 B 的右子树是否相等

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null){
return true;
}

if(p == null || q == null){
return false;
}

return (p.val == q.val)
&& isSameTree(p.left,q.left)
&& isSameTree(p.right,q.right);
}
}
``````

## 对称二叉树

#### 思路一：序列化

``````    1
/ \
2   2
/ \ / \
3  4 4  3
``````

``````/**
* 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) {
String res1 = serializeTreeByPreOrder(root);
String res2 = serializeTreeByPosOrder(root);
return res1.equals(res2);

}

private static String serializeTreeByPreOrder(TreeNode root){
if(root == null){
return "#_";
}
String res = root.val + "_";
res += serializeTreeByPreOrder(root.left);
res += serializeTreeByPreOrder(root.right);
return res;
}

private static String serializeTreeByPosOrder(TreeNode root){
if(root == null){
return "#_";
}
String res = root.val + "_";
res += serializeTreeByPosOrder(root.right);
res += serializeTreeByPosOrder(root.left);
return res;
}
}
``````

#### 思路二： recursion

1. 判断两个指针当前节点值是否相等
2. 判断 A 的右子树与 B 的左子树是否对称
3. 判断 A 的左子树与 B 的右子树是否对称

``````/**
* 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 isMirror(root,root);
}

private boolean isMirror(TreeNode root1,TreeNode root2){
if(root1 == null && root2 == null){
return true;
}
if(root1 == null || root2 == null){
return false;
}

return (root1.val == root2.val)
&& (isMirror(root1.left,root2.right))
&& (isMirror(root1.right,root2.left));
}
}
``````