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

Commitef23e2b

Browse files
Symmetric Tree
1 parent9690690 commitef23e2b

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

‎EASY/src/easy/SymmetricTree.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
packageeasy;
2+
3+
importclasses.TreeNode;
4+
5+
/**101. Symmetric Tree
6+
7+
Total Accepted: 121737
8+
Total Submissions: 346738
9+
Difficulty: Easy
10+
11+
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
12+
13+
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
14+
15+
1
16+
/ \
17+
2 2
18+
/ \ / \
19+
3 4 4 3
20+
21+
But the following [1,2,2,null,3,null,3] is not:
22+
23+
1
24+
/ \
25+
2 2
26+
\ \
27+
3 3
28+
29+
Note:
30+
Bonus points if you could solve it both recursively and iteratively. */
31+
publicclassSymmetricTree {
32+
//a very natural idea flows out using recursion. Cheers.
33+
publicbooleanisSymmetric(TreeNoderoot) {
34+
if(root ==null)returntrue;
35+
returnisSymmetric(root.left,root.right);
36+
}
37+
38+
privatebooleanisSymmetric(TreeNodeleft,TreeNoderight) {
39+
if(left ==null ||right ==null)returnleft ==right;
40+
if(left.val !=right.val)returnfalse;
41+
returnisSymmetric(left.left,right.right) &&isSymmetric(left.right,right.left);
42+
}
43+
44+
publicstaticvoidmain(String...strings) {
45+
SymmetricTreetest =newSymmetricTree();
46+
TreeNoderoot =newTreeNode(1);
47+
System.out.println(test.isSymmetric(root));
48+
}
49+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp