forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request soapyigu#190 from soapyigu/LinkedList
[LinkedList] Add a solution to Flatten Binary Tree to Linked List
- Loading branch information
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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 | ||
} | ||
} |