Leetcode 897.遞增順序查找樹
1 題目描述(Leetcode題目鏈接)
給你一個樹,請你 按中序遍歷 重新排列樹,使樹中最左邊的結點現在是樹的根,並且每個結點沒有左子結點,只有一個右子結點。
輸入:[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 範圍內的唯一整數值。
2 題解
中序遍歷構建。
# 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:
head = TreeNode(0)
p = head
stack = []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
p.right = root
p.left = None
p = p.right
root = root.right
return head.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, tail = None) -> TreeNode:
if not root: return tail
res = self.increasingBST(root.left, root)
root.left = None
root.right = self.increasingBST(root.right, tail)
return res