72. Leetcode 99. 恢复二叉搜索树 (二叉搜索树-中序遍历类)
生活随笔
收集整理的這篇文章主要介紹了
72. Leetcode 99. 恢复二叉搜索树 (二叉搜索树-中序遍历类)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你二叉搜索樹的根節點 root ,該樹中的 恰好 兩個節點的值被錯誤地交換。請在不改變其結構的情況下,恢復這棵樹?。示例 1:輸入:root = [1,3,null,null,2]
輸出:[3,1,null,null,2]
解釋:3 不能是 1 的左孩子,因為 3 > 1 。交換 1 和 3 使二叉搜索樹有效。
示例 2:輸入:root = [3,1,4,null,null,2]
輸出:[2,1,4,null,null,3]
解釋:2 不能在 3 的右子樹中,因為 2 < 3 。交換 2 和 3 使二叉搜索樹有效。# 方法一# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:def recoverTree(self, root: Optional[TreeNode]) -> None:"""Do not return anything, modify root in-place instead."""nodes = []# 中序遍歷二叉樹,將遍歷的結果保存在list中def dfs(root):if not root:return dfs(root.left)nodes.append(root)dfs(root.right)dfs(root)x = Noney = Nonepre = nodes[0]# 掃描遍歷的結果,找出可能存在的錯誤交換節點x和yfor i in range(1,len(nodes)):if pre.val > nodes[i].val:y = nodes[i]if not x:x = prepre = nodes[i]# 如果x和y不為空,則交換兩個節點if x and y:x.val, y.val = y.val,x.val
總結
以上是生活随笔為你收集整理的72. Leetcode 99. 恢复二叉搜索树 (二叉搜索树-中序遍历类)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 70. Leetcode 701. 二叉
- 下一篇: 73. Leetcode 230. 二叉