File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(n)
2
+ // Space Complexity: O(1)
3
+
4
+ /* *
5
+ * Definition for binary tree with next pointer.
6
+ * struct TreeLinkNode {
7
+ * int val;
8
+ * TreeLinkNode *left, *right, *next;
9
+ * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
10
+ * };
11
+ */
12
+ class Solution {
13
+ public:
14
+ void connect (TreeLinkNode *root) {
15
+ for (TreeLinkNode *list, *first; root; root = first) { // enumerate each level of depth
16
+ list = first = NULL ;
17
+ for (; root; root = root->next ) { // enumerate nodes at the same level of depth
18
+ if (!first) first = (root->left )? root->left :root->right ;
19
+ if (root->left ) {
20
+ if (list) list->next = root->left ;
21
+ list = root->left ;
22
+ }
23
+ if (root->right ) {
24
+ if (list) list->next = root->right ;
25
+ list = root->right ;
26
+ }
27
+ }
28
+ }
29
+ }
30
+ };
You can’t perform that action at this time.
0 commit comments