# LeetCode 100 及 101题

## 100. 相同的树

/ \ / \

2 3 2 3

[1,2,3], [1,2,3]

/ \ / \

2 1 1 2

[1,2,1], [1,1,2]

``` 1 /**
2  * Definition for a binary tree node.
3  * public class TreeNode {
4  *     int val;
5  *     TreeNode left;
6  *     TreeNode right;
7  *     TreeNode(int x) { val = x; }
8  * }
9  */
10 class Solution {
11     public boolean isSameTree(TreeNode p, TreeNode q) {
12         if(p == null && q == null)
13             return true;
14         else if(!(p != null && q != null))
15             return false;
16         else {
17             if(p.val == q.val)
18                 return(isSameTree(p.left, q.left) && isSameTree(p.right, q.right));
19             else
20                 return false;
21         }
22     }
23 }```

## 101. 对称二叉树

1

/ \

2 2

/ \ / \

3 4 4 3

1

/ \

2 2

\ \

3 3

``` 1 /**
2  * Definition for a binary tree node.
3  * public class TreeNode {
4  *     int val;
5  *     TreeNode left;
6  *     TreeNode right;
7  *     TreeNode(int x) { val = x; }
8  * }
9  */
10 class Solution {
11     public boolean isSymmetric(TreeNode root) {
12         if(root == null)
13             return true;
14         else
15             return isMirror(root.left, root.right);
16     }
17     public boolean isMirror(TreeNode m, TreeNode n) {
18         if(m == null & n == null)
19             return true;
20         else if(m !=null && n !=null && m.val == n.val)
21             return (isMirror(m.left, n.right) && isMirror(m.right, n.left));
22         else
23             return false;
24     }
25 }```

``` 1 /**
2  * Definition for a binary tree node.
3  * public class TreeNode {
4  *     int val;
5  *     TreeNode left;
6  *     TreeNode right;
7  *     TreeNode(int x) { val = x; }
8  * }
9  */
10 class Solution {
11     public boolean isSymmetric(TreeNode root) {
12         if (root == null)
13             return true;
14         List<TreeNode> l1 = new ArrayList<TreeNode>();
15         List<TreeNode> l2 = new ArrayList<TreeNode>();
18         int cur1 = 0;
19         int cur2 = 0;
20         while(cur1 < l1.size() && cur2 < l2.size()) {
21             if(l1.get(cur1) == null && l2.get(cur2) == null) {
22                 cur1++;
23                 cur2++;
24                 continue;
25             }
26             else if(l1.get(cur1) == null || l2.get(cur2) == null)
27                 return false;
28             else if(l1.get(cur1).val == l2.get(cur2).val) {
33             }
34             else
35                 return false;
36         }
37         return true;
38     }
39 }```

40 篇文章17 人订阅

0 条评论