File tree Expand file tree Collapse file tree 1 file changed +9
-40
lines changed Expand file tree Collapse file tree 1 file changed +9
-40
lines changed Original file line number Diff line number Diff line change 4
4
5
5
public class Main {
6
6
7
- public boolean isSymmetric (TreeNode left , TreeNode right ) {
8
- if (left == null && right == null ) {
9
- return true ;
10
- }
11
- if (left == null || right == null ) {
12
- return false ;
13
- }
14
-
15
- Stack <TreeNode > stack1 = new Stack <TreeNode >();
16
- Stack <TreeNode > stack2 = new Stack <TreeNode >();
17
-
18
- while (!stack1 .isEmpty () || left != null ) {
19
- if (left != null ) {
20
- if (right == null ) {
21
- return false ;
22
- }
23
- if (left .val != right .val ) {
24
- return false ;
25
- }
26
- stack1 .push (left );
27
- stack2 .push (right );
28
- left = left .left ;
29
- right = right .right ;
30
- } else {
31
- if (right != null ) {
32
- return false ;
33
- }
34
- if (stack2 .isEmpty ()) {
35
- return false ;
36
- }
37
- left = stack1 .pop ().right ;
38
- right = stack2 .pop ().left ;
39
- }
40
- }
41
- return stack2 .isEmpty () && right == null ;
42
- }
43
-
44
- public boolean isSymmetric (TreeNode root ) {
7
+ public int countNodes (TreeNode root ) {
45
8
if (root == null ) {
46
- return true ;
9
+ return 0 ;
10
+ }
11
+ int left = 0 , right = 0 ;
12
+ for (TreeNode node = root ; node != null ; node = node .left , left ++);
13
+ for (TreeNode node = root ; node != null ; node = node .right , right ++);
14
+ if (left == right ) {
15
+ return (1 << left ) - 1 ;
47
16
}
48
- return isSymmetric (root .left , root .right );
17
+ return countNodes (root .left ) + countNodes ( root .right ) + 1 ;
49
18
}
50
19
51
20
public static void main (String [] args ) {
You can’t perform that action at this time.
0 commit comments