Binary Tree Upside Down – Python 3 (Week 12 – 16)

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: the root of binary tree
    @return: new root
    """
    def upsideDownBinaryTree(self, root):
        # write your code here
        
        if root == None:
            return None
        return self.dfs(root)
        
        
    def dfs(self, cur):
        if cur.left == None:
            return cur
        newroot = self.dfs(cur.left)
        cur.left.right = cur
        cur.left.left = cur.right
        cur.left = None
        cur.right = None
        return newroot

Time O(h). Space O(h).

Leave a comment

Design a site like this with WordPress.com
Get started