【LeetCode】156. Binary Tree Upside Down

解法:

    在每個節點p,使節點p的左子樹根節點爲該節點右兄弟節點,節點p的右子樹根節點爲該節點的父節點。即可。類似反轉鏈表。

Python源碼:

Runtime: 28 ms, faster than 5.57% of Python online submissions for Binary Tree Upside Down.

Memory Usage: 11.8 MB, less than 50.00% of Python online submissions for Binary Tree Upside Down.

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def upsideDownBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        p = root
        parent = None
        parent_right = None
        while p != None:
            left = p.left
            p.left = parent_right
            parent_right = p.right
            p.right = parent
            parent = p
            p = left
        return parent

我的心路:

    首先爲了讀懂題,拓展了原例子,畫得更長一些,有

   

    一個直接的方法是,遍歷並保存字典和列表,創建新樹。時間複雜度O(n),空間複雜度O(n),有額外的空間開銷。效果還不錯。

Runtime: 16 ms, faster than 81.24% of Python online submissions for Binary Tree Upside Down.

Memory Usage: 11.8 MB, less than 50.00% of Python online submissions for Binary Tree Upside Down.

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def upsideDownBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if root == None:
            return root
        node = root
        trunk_nodes = []
        branch_nodes = []
        while node != None:
            trunk_nodes.append(node.val)
            if node.right != None:
                branch_nodes.append(node.right.val)
            else:
                branch_nodes.append('0')
            node = node.left
        branch_nodes.pop()
        i = len(trunk_nodes)
        dummy = TreeNode(0)
        cur = dummy
        while branch_nodes:
            new_node = TreeNode(trunk_nodes.pop())
            branch_val = branch_nodes.pop()
            print(branch_val)
            if branch_val != '0':
                new_node.left = TreeNode(branch_val)
            cur.right = new_node
            cur = new_node
        while trunk_nodes:
            new_node = TreeNode(trunk_nodes.pop())
            cur.right = new_node
            cur = new_node
                
        return dummy.right

   採取原地轉換的方式,從root開始,在根節點創建左子樹值的新節點使之右子節點指向當前根節點,左子節點指向當前根節點的右子節點,返回傳入原左子樹根節點的遞歸函數。不知如何利用遞歸函數傳遞節點間的父子關係,沒能實現。

    觀察推薦解法發現,推薦解法對題目的理解和觀察更準確,所以代碼更簡潔。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章