You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/1600-1699/1609.Even Odd Tree/README_EN.md
+37-15Lines changed: 37 additions & 15 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -60,7 +60,11 @@ Node values in level 2 must be in strictly increasing order, so the tree is not
60
60
61
61
## Solutions
62
62
63
-
### Solution 1
63
+
### Solution 1: BFS
64
+
65
+
BFS traverses level by level. Each level is judged by its parity. The node values at each level are either all even or all odd, and they are strictly increasing or decreasing.
66
+
67
+
The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the binary tree.
64
68
65
69
<!-- tabs:start -->
66
70
@@ -114,7 +118,7 @@ class Solution {
114
118
Deque<TreeNode> q =newArrayDeque<>();
115
119
q.offer(root);
116
120
while (!q.isEmpty()) {
117
-
int prev = even ?0:1000000;
121
+
int prev = even ?0:1000001;
118
122
for (int n = q.size(); n >0; --n) {
119
123
root = q.pollFirst();
120
124
if (even && (root.val %2==0|| prev >= root.val)) {
DFS performs a pre-order traversal of the binary tree, and similarly judges whether it meets the conditions based on the parity of the layer where the node is located. During the traversal, a hash table is used to record the node value that was most recently visited at each layer.
233
+
234
+
The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the binary tree.
219
235
220
236
<!-- tabs:start -->
221
237
@@ -272,7 +288,7 @@ class Solution {
272
288
returntrue;
273
289
}
274
290
boolean even = i %2==0;
275
-
int prev = d.getOrDefault(i, even ?0:1000000);
291
+
int prev = d.getOrDefault(i, even ?0:1000001);
276
292
if (even && (root.val %2==0|| prev >= root.val)) {
0 commit comments