LeetCode 897 Increasing Order Search Tree 解题报告
Posted yao1996
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 897 Increasing Order Search Tree 解题报告相关的知识,希望对你有一定的参考价值。
题目要求
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.
题目分析及思路
题目给出一棵树,要求重新对树进行排序,使得树中最左边的结点是树的根,并且每一个结点没有左孩子,只有一个右孩子。可以先得到已知树的中序遍历,再依次创建新的结点并让每一个结点只有一个右孩子。
python代码
# 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 解题报告的主要内容,如果未能解决你的问题,请参考以下文章
897. Increasing Order Search Tree
897. Increasing Order Search Tree
leetcode-334 Increasing Triplet Subsequence 解题记录
leetcode 334. Increasing Triplet Subsequence