0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Leetcode #156: Binary Tree Upside Down

0
Posted at

Solution 1: Recursively

func upsideDownBinaryTree(_ root: TreeNode?) -> TreeNode? {
    if root == nil || root?.left == nil {
        return root
    }
    let res = upsideDownBinaryTree(root?.left)
    root?.left?.left = root?.right
    root?.left?.right = root
    root?.left = nil
    root?.right = nil
    return res
}

Solution 2: Iteratively

func upsideDownBinaryTree(_ root: TreeNode?) -> TreeNode? {
    var current = root
    var pre: TreeNode?
    var next: TreeNode?
    var tmp: TreeNode?
    while current != nil {
        next = current?.left
        current?.left = tmp
        tmp = current?.right
        current?.right = pre
        pre = current
        current = next
    }
    return pre
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?