-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSymmetricTree.java
More file actions
44 lines (40 loc) · 1014 Bytes
/
SymmetricTree.java
File metadata and controls
44 lines (40 loc) · 1014 Bytes
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
package binary_tree;
/**
* @Author: Wenhang Chen
* @Description:给定一个二叉树,检查它是否是镜像对称的。 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
* <p>
* 1
* / \
* 2 2
* / \ / \
* 3 4 4 3
* 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
* <p>
* 1
* / \
* 2 2
* \ \
* 3 3
* @Modified by:
*/
public class SymmetricTree {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public boolean isSymmetric(TreeNode root) {
// 对于树的操作,传两个参数有时候会很方便
return isMirror(root, root);
}
public boolean isMirror(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return true;
if (t1 == null || t2 == null) return false;
return (t1.val == t2.val)
&& isMirror(t1.right, t2.left)
&& isMirror(t1.left, t2.right);
}
}