5/01/2021

[LeetCode] 156. Binary Tree Upside Down

 Problem : https://leetcode.com/problems/binary-tree-upside-down/

Although it says every node has either 0 or 2 children in the given example. The input tree may only has left sub-tree.


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def upsideDownBinaryTree(self, root: TreeNode) -> TreeNode:
        
        def helper(node):
            if node and node.left:
                lt = node.left
                node.left = None
                lt = helper(lt)
                
                rt = node.right
                node.right = None
                rt = helper(rt)
                   
                np = lt
                while np.right:
                    np = np.right
                
                np.left = rt
                np.right = node
                   
                return lt
                
            else:
                return node
            
        
        return helper(root)

No comments:

Post a Comment