File tree Expand file tree Collapse file tree 2 files changed +99
-0
lines changed
lcof2/剑指 Offer II 052. 展平二叉搜索树 Expand file tree Collapse file tree 2 files changed +99
-0
lines changed Original file line number Diff line number Diff line change @@ -326,6 +326,58 @@ struct TreeNode* increasingBST(struct TreeNode* root) {
326326}
327327```
328328
329+ #### Swift
330+
331+ ```swift
332+ /* class TreeNode {
333+ * var val: Int
334+ * var left: TreeNode?
335+ * var right: TreeNode?
336+ * init() {
337+ * self.val = 0
338+ * self.left = nil
339+ * self.right = nil
340+ * }
341+ * init(_ val: Int) {
342+ * self.val = val
343+ * self.left = nil
344+ * self.right = nil
345+ * }
346+ * init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
347+ * self.val = val
348+ * self.left = left
349+ * self.right = right
350+ * }
351+ * }
352+ */
353+
354+ class Solution {
355+ func increasingBST(_ root: TreeNode?) -> TreeNode? {
356+ var head: TreeNode? = nil
357+ var tail: TreeNode? = nil
358+ var stack = [TreeNode]()
359+ var cur = root
360+
361+ while !stack.isEmpty || cur != nil {
362+ while cur != nil {
363+ stack.append(cur!)
364+ cur = cur?.left
365+ }
366+ cur = stack.removeLast()
367+ if head == nil {
368+ head = cur
369+ } else {
370+ tail?.right = cur
371+ }
372+ tail = cur
373+ cur?.left = nil
374+ cur = cur?.right
375+ }
376+ return head
377+ }
378+ }
379+ ```
380+
329381<!-- tabs:end -->
330382
331383<!-- solution:end -->
Original file line number Diff line number Diff line change 1+ /* class TreeNode {
2+ * var val: Int
3+ * var left: TreeNode?
4+ * var right: TreeNode?
5+ * init() {
6+ * self.val = 0
7+ * self.left = nil
8+ * self.right = nil
9+ * }
10+ * init(_ val: Int) {
11+ * self.val = val
12+ * self.left = nil
13+ * self.right = nil
14+ * }
15+ * init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
16+ * self.val = val
17+ * self.left = left
18+ * self.right = right
19+ * }
20+ * }
21+ */
22+
23+ class Solution {
24+ func increasingBST( _ root: TreeNode ? ) -> TreeNode ? {
25+ var head : TreeNode ? = nil
26+ var tail : TreeNode ? = nil
27+ var stack = [ TreeNode] ( )
28+ var cur = root
29+
30+ while !stack. isEmpty || cur != nil {
31+ while cur != nil {
32+ stack. append ( cur!)
33+ cur = cur? . left
34+ }
35+ cur = stack. removeLast ( )
36+ if head == nil {
37+ head = cur
38+ } else {
39+ tail? . right = cur
40+ }
41+ tail = cur
42+ cur? . left = nil
43+ cur = cur? . right
44+ }
45+ return head
46+ }
47+ }
You can’t perform that action at this time.
0 commit comments