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.
[Tree] Add a solution to Binary Tree Upside Down
- Loading branch information
Yi Gu
committed
Dec 7, 2016
1 parent
f529e77
commit 6649eff
Showing
1 changed file
with
37 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,37 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/binary-tree-upside-down/ | ||
* Primary idea: Mark left one as current node, change its left and right and | ||
* keep going to right until to the leaf | ||
* 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 BinaryTreeUpsideDown { | ||
func upsideDownBinaryTree(_ root: TreeNode?) -> TreeNode? { | ||
var parent: TreeNode? | ||
var node: TreeNode? = root | ||
var right: TreeNode? | ||
|
||
while node != nil { | ||
let left = node!.left | ||
node!.left = right | ||
right = node!.right | ||
node!.right = parent | ||
parent = node | ||
node = left | ||
} | ||
|
||
return parent | ||
} | ||
} |