Skip to content

Commit f4e7012

Browse files
committed
fd
1 parent 2988771 commit f4e7012

File tree

1 file changed

+9
-40
lines changed

1 file changed

+9
-40
lines changed

leetcode/src/Main.java

Lines changed: 9 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -4,48 +4,17 @@
44

55
public class Main {
66

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) {
458
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;
4716
}
48-
return isSymmetric(root.left, root.right);
17+
return countNodes(root.left) + countNodes(root.right) + 1;
4918
}
5019

5120
public static void main(String[] args) {

0 commit comments

Comments
 (0)