LeetCode-Python-99. ツリーの復元

1241 ワード

ツリー内の2つのノードが誤って交換されました.
構造を変えずに、この木を復元してください.
例1:
入力:[1,3,null,null,2]
   1   / 3   \   2
出力:[3,1,null,null,2]
3/12の例2:
入力:[3,1,4,null,null,2]
  3  /\1   4   /  2
出力:[2,1,4,null,null,3]
2/1 4/3ステップ:
O(n)空間複雑度を用いた解法は容易に実現できる.定数空間だけを使う解決策を考え出せますか?
ソース:力ボタン(LeetCode)リンク:https://leetcode-cn.com/problems/recover-binary-search-tree著作権はインターネットの所有に帰属する.商業転載は公式の授権に連絡してください.非商業転載は出典を明記してください.
考え方:
まず,すべてのノードの値を中順に遍歴して得,その後,中順遍歴の結果を並べ替え,並べ替えた結果を記入する.
class Solution(object):
    def recoverTree(self, root):
        """
        :type root: TreeNode
        :rtype: None Do not return anything, modify root in-place instead.
        """
        def inOrder(node):
            if not node:
                return []
            return inOrder(node.left) + [node.val] + inOrder(node.right)
        
        inorder = inOrder(root)
        inorder.sort()
        
        self.idx = 0
        def change(node):
            if not node:
                return
            change(node.left)
            node.val = inorder[self.idx]
            self.idx += 1
            change(node.right)
            
        change(root)
        return root