File tree 1 file changed +52
-0
lines changed
1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change @@ -65,3 +65,55 @@ var connect = function(root) {
65
65
nextRow = [ ] ;
66
66
}
67
67
} ;
68
+
69
+
70
+ // O(1) space solution
71
+
72
+ /**
73
+ * Definition for binary tree with next pointer.
74
+ * function TreeLinkNode(val) {
75
+ * this.val = val;
76
+ * this.left = this.right = this.next = null;
77
+ * }
78
+ */
79
+
80
+ /**
81
+ * @param {TreeLinkNode } root
82
+ * @return {void } Do not return anything, modify tree in-place instead.
83
+ */
84
+ var connect = function ( root ) {
85
+ let nextHead = null ;
86
+ let cur = root ;
87
+ let nextCur = null ;
88
+
89
+ while ( cur !== null ) {
90
+
91
+ while ( cur !== null ) {
92
+ if ( cur . left ) {
93
+ if ( ! nextHead ) {
94
+ nextHead = cur . left ;
95
+ nextCur = nextHead ;
96
+ } else {
97
+ nextCur . next = cur . left ;
98
+ nextCur = nextCur . next ;
99
+ }
100
+ }
101
+
102
+ if ( cur . right ) {
103
+ if ( ! nextHead ) {
104
+ nextHead = cur . right ;
105
+ nextCur = nextHead ;
106
+ } else {
107
+ nextCur . next = cur . right ;
108
+ nextCur = nextCur . next ;
109
+ }
110
+ }
111
+
112
+ cur = cur . next ;
113
+ }
114
+
115
+ cur = nextHead ;
116
+ nextHead = null ;
117
+ nextCur = null ;
118
+ }
119
+ } ;
You can’t perform that action at this time.
0 commit comments