题目链接:https://leetcode-cn.com/problems/increasing-order-search-tree/
题意
给出一个二叉搜索树,求将里面的数值全部取出并按顺序构成一条往右的链的一个树
题解
直接中序遍历得到序列,然后插入即可
code
def dfs(v: TreeNode) -> list:
if not v:
return []
res = dfs(v.left)
res.append(v.val)
res = res+dfs(v.right)
return res
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
res = dfs(root)
t = TreeNode(res[0], None, None)
fa = t
for i in range(1, len(res)):
tmp = TreeNode(res[i], None, None)
fa.right = tmp
fa = tmp
return t