标签:ever turn append 要求 中序遍历 mos not extend rate
Given a 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.
题目给出一棵树,要求重新对树进行排序,使得树中最左边的结点是树的根,并且每一个结点没有左孩子,只有一个右孩子。可以先得到已知树的中序遍历,再依次创建新的结点并让每一个结点只有一个右孩子。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def increasingBST(self, root: ‘TreeNode‘) -> ‘TreeNode‘:
def inorder(root):
order = []
if not root:
return order
order.extend(inorder(root.left))
order.append(root.val)
order.extend(inorder(root.right))
return order
in_order = inorder(root)
nodes = []
for v in in_order:
nodes.append(TreeNode(v))
for i, v in enumerate(nodes):
if (i+1) == len(in_order):
break
else:
v.right = nodes[i+1]
return nodes[0]
LeetCode 897 Increasing Order Search Tree 解题报告
标签:ever turn append 要求 中序遍历 mos not extend rate
原文地址:https://www.cnblogs.com/yao1996/p/10373680.html