99. Recover Binary Search Tree 恢复二叉搜索树
生活随笔
收集整理的這篇文章主要介紹了
99. Recover Binary Search Tree 恢复二叉搜索树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
二叉搜索樹中的兩個節點被錯誤地交換。
請在不改變其結構的情況下,恢復這棵樹。
示例 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/3進階:
中序遍歷
提到二叉搜索樹,首先想到中序遍歷,因為BST的中序遍歷結果是排好序的,所以將排序的中序遍歷結果和未排序的中序遍歷結果中不同的節點交換即可。
Code
def recoverTree(self, root: TreeNode) -> None:"""Do not return anything, modify root in-place instead."""Trees = lambda x: [] if not x else Trees(x.left) + [x] + Trees(x.right)a = Trees(root)sa = sorted(a, key=lambda x: x.val)temp = [a[i] for i in range(len(a)) if a[i] != sa[i]]temp[0].val, temp[1].val = temp[1].val, temp[0].val總結
以上是生活随笔為你收集整理的99. Recover Binary Search Tree 恢复二叉搜索树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2020\Simulation_1\2.
- 下一篇: 93. Restore IP Addre