Skip to content

Commit af117e7

Browse files
authored
Merge pull request gzc426#14 from Syuan-Cheng/Syuan-Cheng-patch-10
Create syuan.md
2 parents a9dee38 + 804f5c5 commit af117e7

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

2018.12.04-leetcode101/syuan.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
##### 题目
2+
3+
```
4+
给定一个二叉树,检查它是否是镜像对称的。
5+
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+
16+
1
17+
/ \
18+
2 2
19+
\ \
20+
3 3
21+
```
22+
##### 代码
23+
递归
24+
```
25+
public boolean isSymmetric(TreeNode root) {
26+
if (root==null) {
27+
return true;
28+
}else{
29+
return isSymmetric(root.left,root.right);
30+
}
31+
}
32+
33+
public boolean isSymmetricCore(TreeNode leftNode, TreeNode rightNode){
34+
if (leftNode==null && rightNode==null) {
35+
return true;
36+
}
37+
if (leftNode.val!=rightNode.val || leftNode==null || rightNode==null) {
38+
return false;
39+
}
40+
return isSymmetricCore(leftNode.left,rightNode.right) && isSymmetricCore(leftNode.right,rightNode.left);
41+
}
42+
```
43+
##### 非递归法
44+
45+
```
46+
class Solution {
47+
public boolean isSymmetric(TreeNode root) {
48+
if(root == null) return true;
49+
Stack<TreeNode> stack = new Stack<TreeNode>();
50+
stack.push(root.left);
51+
stack.push(root.right);
52+
while(!stack.empty()) {
53+
TreeNode right = stack.pop();
54+
TreeNode left = stack.pop();
55+
if (left == null && right == null) continue;
56+
else if (left == null || right == null || right.val != left.val) return false;
57+
stack.push(left.left);
58+
stack.push(right.right);
59+
stack.push(left.right);
60+
stack.push(right.left);
61+
}
62+
return true;
63+
}
64+
}
65+
```

0 commit comments

Comments
 (0)