【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开始,在根节点创建左子树值的新节点使之右子节点指向当前根节点,左子节点指向当前根节点的右子节点,返回传入原左子树根节点的递归函数。不知如何利用递归函数传递节点间的父子关系,没能实现。

    观察推荐解法发现,推荐解法对题目的理解和观察更准确,所以代码更简洁。

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