-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0099-recover-binary-search-tree.py
More file actions
48 lines (39 loc) · 1.15 KB
/
0099-recover-binary-search-tree.py
File metadata and controls
48 lines (39 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# time complexity: O(n)
# space complexity: O(n)
from typing import Optional
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:
nodeList = []
binaryList = []
def inorder(node):
if not node:
return
if node.left:
inorder(node.left)
nodeList.append(node.val)
if node.right:
inorder(node.right)
def traverseChange(node):
if not node:
return
currVal = node.val
currIdx = nodeList.index(currVal)
node.val = binaryList[currIdx]
if node.left:
traverseChange(node.left)
if node.right:
traverseChange(node.right)
inorder(root)
binaryList = sorted(nodeList)
traverseChange(root)
return root
root = TreeNode(3)
root.left = TreeNode(1)
root.right = TreeNode(4)
root.right.left = TreeNode(2)
print(Solution().recoverTree(root))