-
Notifications
You must be signed in to change notification settings - Fork 1
/
101.对称二叉树.java
74 lines (72 loc) · 1.49 KB
/
101.对称二叉树.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* @lc app=leetcode.cn id=101 lang=java
*
* [101] 对称二叉树
*
* https://leetcode-cn.com/problems/symmetric-tree/description/
*
* algorithms
* Easy (47.76%)
* Likes: 431
* Dislikes: 0
* Total Accepted: 52.3K
* Total Submissions: 108.2K
* Testcase Example: '[1,2,2,3,4,4,3]'
*
* 给定一个二叉树,检查它是否是镜像对称的。
*
* 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
*
* 1
* / \
* 2 2
* / \ / \
* 3 4 4 3
*
*
* 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
*
* 1
* / \
* 2 2
* \ \
* 3 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) {
if (root == null) {
return true;
}
return isSymmetric(root.left, root.right);
}
public boolean isSymmetric(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
if (!isSymmetric(p.left, q.right)) {
return false;
}
if (p.val != q.val) {
return false;
}
return isSymmetric(p.right, q.left);
}
}