二叉搜尋樹中的兩個節點被錯誤地交換。請在不改變其結構的情況下,恢復這棵樹。
示例 1:
輸入: [1,3,null,null,2]1/
3\2輸出: [3,1,null,null,2]3/
1\2分析:
1.假如乙個bst中序是4,2,3,1,我們發現要交換1和4,找到1和4並交換即可,通過觀察發現,第乙個要交換的節點是第一次前乙個數大於當前數,第二個節點是第二次前乙個數大於當前的數,所以我們需要維持乙個pre指標指向前乙個節點
2.如果用o(n)的輔助空間可以這麼做,利用bst中序有序的特點,將節點全部存起來,將值排序後再分別賦值
# 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 recovertree(self, root):
self.firstnode,self.secondnode=none,none
self.prenone=treenode(float("-inf"))
def dfs(t):
if not t:return
dfs(t.left)
if self.firstnode==none and self.prenone.val >= t.val:
self.firstnode=self.prenone
if self.firstnode and self.prenone.val >= t.val:
self.secondnode=t
self.prenone=t
dfs(t.right)
dfs(root)
self.firstnode.val,self.secondnode.val=self.secondnode.val,self.firstnode.val
# 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 recovertree(self, root):
tree=
val=
def dfs(t):
if not t:return
dfs(t.left)
dfs(t.right)
dfs(root)
val=sorted(val)
for i in range(len(val)):
tree[i].val=val[i]
99 恢復二叉搜尋樹
二叉搜尋樹中的兩個節點被錯誤地交換。請在不改變其結構的情況下,恢復這棵樹。示例 2 輸入 3,1,4,null,null,2 3 1 4 2輸出 2,1,4,null,null,3 2 1 4 3高階 使用 o n 空間複雜度的解法很容易實現。你能想出乙個只使用常數空間的解決方案嗎?在二叉搜尋樹中,...
99 恢復二叉搜尋樹
二叉搜尋樹中的兩個節點被錯誤地交換。請在不改變其結構的情況下,恢復這棵樹。二叉搜尋樹中序遍歷為有序陣列,如 1,2,3,4,5,6 交換其中不相鄰任兩個,變成 1,6,3,4,5,2 會有兩個逆序對 6,3 和 5,2 可以看出交換位置為前一逆序對的前乙個元素和後一逆序對的後一元素。相鄰的話只有乙個...
99 恢復二叉搜尋樹
二叉搜尋樹中的兩個節點被錯誤地交換。請在不改變其結構的情況下,恢復這棵樹。示例 1 輸入 1,3,null,null,2 1 3 2 輸出 3,1,null,null,2 3 1 2示例 2 輸入 3,1,4,null,null,2 3 1 4 2輸出 2,1,4,null,null,3 2 1 4...