题目描述
Category:Easy Tree
Given a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.
题目理解
给定一棵二叉搜索树,重新用中序遍历组织这棵树,最左边的节点是这棵新树的根节点,每个节点都没有左子节点,只有一个右子节点。
解题思路
中序遍历时修改指针
使用prev指针一直指向了构造出来的这个新树的最右下边的节点,在中序遍历过程中把当前节点的左指针给设置为None,然后把当前节点放到新树的右下角,这样类似于一个越来越长的链表的构建过程。
思路借鉴:https://blog.csdn.net/fuxuemingzhu/article/details/82349263
class Solution:
# Runtime: 32ms 91.30% MemoryUsage: 12.9MB 100.00%
def increasingBST1(self, root: TreeNode) -> TreeNode:
dummy = TreeNode(-1)
self.prev = dummy
self.in_Order(root)
return dummy.right
def in_Order(self, root):
if not root:
return None
self.in_Order(root.left)
root.left = None
self.prev.right = root
self.prev = self.prev.right
self.in_Order(root.right)
哦豁,这个递归写得好高级哦!!!
MyMethod
基础思想:中序遍历整棵树,用res数组依次记录每个节点的值,然后遍历res数组,重建树,建树规则如题所述。
class Solution:
# Runtime: 28ms 96.67% MemoryUsage: 12.9MB 100.00%
def increasingBST(self, root: TreeNode) -> TreeNode:
if root is None:
return
res = []
self.inOrder(root, res)
new_root = TreeNode(res[0])
res.pop(0)
queue = [new_root]
while queue:
cur_node = queue.pop(0)
new_node = TreeNode(res[0])
res = res[1:]
if res == []:
return new_root
cur_node.left = None
cur_node.right = new_node
queue.append(cur_node.right)
return new_root
def inOrder(self, root, res):
if root is None:
return
self.inOrder(root.left, res)
res.append(root.val)
self.inOrder(root.right, res)
没想到这么基础的方法,效果还不错,嘻嘻
Time
2020.3.26 今天心情有点点好