Skip to content

Commit a78337b

Browse files
author
luzhicheng
committed
更新md
更新md
1 parent 3867ec8 commit a78337b

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed

leetcode_tree/main.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
## LeetCode树
22
1. [相同的树](相同的树.md)
3+
2. [对称二叉树](对称二叉树.md)

leetcode_tree/对称二叉树.md

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
## 对称二叉树
2+
给定一个二叉树,检查它是否是镜像对称的。
3+
4+
#### 示例
5+
```python
6+
# 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
7+
8+
1
9+
/ \
10+
2 2
11+
/ \ / \
12+
3 4 4 3
13+
14+
# 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
15+
1
16+
/ \
17+
2 2
18+
\ \
19+
3 3
20+
```
21+
22+
#### 代码
23+
**迭代**
24+
25+
[相同的树](相同的树.md)类似,遍历树节点,保存到队列中,然后依次比较
26+
27+
* 根节点为None,直接返回True
28+
* 两个队列分别存储根节点的左子节点与右子节点
29+
* 分别从两个队列中取出一个节点,进行比较
30+
* 如果两个节点一个为None,一个不为None,则说明不对称,直接返回False
31+
* 如果两个节点都不为None,比较节点值,如果值不相等,则说明不对称,直接返回False
32+
* 如果值相等,按照顺序,添加节点的子节点到队列中,等待下一轮比较
33+
34+
```python
35+
class Solution:
36+
def isSymmetric(self, root: TreeNode) -> bool:
37+
if not root:
38+
return True
39+
left = root.left
40+
right = root.right
41+
42+
queue1 = deque([left])
43+
queue2 = deque([right])
44+
45+
while queue1 and queue2:
46+
node1 = queue1.popleft()
47+
node2 = queue2.popleft()
48+
49+
if (not node1) ^ (not node2):
50+
# 两个子节点一个为None,一个不为None
51+
return False
52+
53+
if node1 is None and node2 is None:
54+
# 两个子节点都是None
55+
continue
56+
57+
if node1.val != node2.val:
58+
return False
59+
60+
left1 = node1.left
61+
right1 = node1.right
62+
left2 = node2.left
63+
right2 = node2.right
64+
65+
queue1.append(left1)
66+
queue2.append(right2)
67+
queue1.append(right1)
68+
queue2.append(left2)
69+
70+
return not queue1 and not queue2
71+
```
72+
73+
**递归**
74+
75+
```python
76+
class Solution:
77+
78+
def check(self, p, q):
79+
if (not p) ^ (not q):
80+
return False
81+
if p is None and q is None:
82+
return True
83+
84+
if p.val != q.val:
85+
return False
86+
87+
return self.check(p.left, q.right) and self.check(p.right, q.left)
88+
89+
def isSymmetric(self, root: TreeNode) -> bool:
90+
return self.check(root, root)
91+
```

0 commit comments

Comments
 (0)