Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit5ac2711

Browse files
committed
tree
1 parent24648a0 commit5ac2711

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

‎tree/IsSymmetric.java

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
packageAlgorithms.tree;
2+
3+
importjava.util.Stack;
4+
5+
publicclassIsSymmetric {
6+
/**
7+
* Definition for binary tree public class TreeNode { int val; TreeNode
8+
* left; TreeNode right; TreeNode(int x) { val = x; } }
9+
*/
10+
// solution 1:
11+
publicbooleanisSymmetric(TreeNoderoot) {
12+
if (root ==null) {
13+
returntrue;
14+
}
15+
16+
returnisSymmetricTree(root.left,root.right);
17+
}
18+
19+
/*
20+
* 判断两个树是否互相镜像 (1) 根必须同时为空,或是同时不为空
21+
*
22+
* 如果根不为空: (1).根的值一样 (2).r1的左树是r2的右树的镜像 (3).r1的右树是r2的左树的镜像
23+
*/
24+
publicbooleanisSymmetricTree1(TreeNoderoot1,TreeNoderoot2) {
25+
if (root1 ==null &&root2 ==null) {
26+
returntrue;
27+
}
28+
29+
if (root1 ==null ||root2 ==null) {
30+
returnfalse;
31+
}
32+
33+
returnroot1.val ==root2.val
34+
&&isSymmetricTree(root1.left,root2.right)
35+
&&isSymmetricTree(root1.right,root2.left);
36+
}
37+
38+
// solution 2:
39+
publicbooleanisSymmetricTree(TreeNoderoot1,TreeNoderoot2) {
40+
if (root1 ==null &&root2 ==null) {
41+
returntrue;
42+
}
43+
44+
if (root1 ==null ||root2 ==null) {
45+
returnfalse;
46+
}
47+
48+
Stack<TreeNode>s1 =newStack<TreeNode>();
49+
Stack<TreeNode>s2 =newStack<TreeNode>();
50+
51+
// 一定记得初始化
52+
s1.push(root1);
53+
s2.push(root2);
54+
55+
while (!s1.isEmpty() && !s2.isEmpty()) {
56+
TreeNodecur1 =s1.pop();
57+
TreeNodecur2 =s2.pop();
58+
59+
if (cur1.val !=cur2.val) {
60+
returnfalse;
61+
}
62+
63+
if (cur1.left !=null &&cur2.right !=null) {
64+
s1.push(cur1.left);
65+
s2.push(cur2.right);
66+
}elseif (!(cur1.left ==null &&cur2.right ==null)) {
67+
returnfalse;
68+
}
69+
70+
if (cur1.right !=null &&cur2.left !=null) {
71+
s1.push(cur1.right);
72+
s2.push(cur2.left);
73+
}elseif (!(cur1.right ==null &&cur2.left ==null)) {
74+
returnfalse;
75+
}
76+
}
77+
78+
returntrue;
79+
}
80+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp