给定一个树,
按中序遍历
重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。
示例 :
输入:[5,3,6,2,4,null,8,1,null,null,null,7,9]
5
/ \
3 6
/ \ \
2 4 8
/ / \
1 7 9
输出:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
1
\
2
\
3
\
4
\
5
\
6
\
7
\
8
\
9
提示:
- 给定树中的结点数介于 1 和 100 之间。
- 每个结点都有一个从 0 到 1000 范围内的唯一整数值。
中序遍历,然后新建一棵树
# 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 increasingBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
mid = []
def midOrd(root):
if root:
midOrd(root.left)
mid.append(root.val)
midOrd(root.right)
midOrd(root)
ans = TreeNode(0)
p = ans
for i in mid:
p.right = TreeNode(i)
p = p.right
return ans.right
借助栈模拟中序遍历
# 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:
s = []
ans = TreeNode(0)
p = ans
while s or root:
if root:
s.append(root)
root = root.left
else:
cur = s.pop()
root = cur.right
cur.left = None
p.right = cur
p = p.right
return ans.right
还有这种神仙递归
# 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 fun(self, root, tail = None):
if not root:
return tail
ans = self.fun(root.left, root)
root.left = None
root.right = self.fun(root.right, tail)
return ans
def increasingBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
return self.fun(root, None)
版权声明:本文为PegasiTIO原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。