forked from NilaakashSingh/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FlattenBinaryTreeLinkedList.swift
47 lines (42 loc) · 1.16 KB
/
FlattenBinaryTreeLinkedList.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Question Link: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
* Primary idea: Reset left to nil and change current node to left child every time
* Time Complexity: O(n), Space Complexity: O(1)
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class FlattenBinaryTreeLinkedList {
func flatten(_ root: TreeNode?) {
helper(root)
}
private func helper(_ node: TreeNode?) -> TreeNode? {
var node = node
if node == nil {
return node
}
if node!.left == nil && node!.right == nil {
return node
}
let left = node!.left, right = node!.right
node!.left = nil
if let left = left {
node!.right = left
node = helper(left)
}
if let right = right {
node!.right = right
node = helper(right)
}
return node
}
}