Skip to content

Commit a008fcf

Browse files
author
Partho Biswas
committed
99_Recover_Binary_Search_Tree
1 parent af9956b commit a008fcf

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,7 @@ Check this [golden](https://tinyurl.com/ujopecz) post.
446446
|12| **[449. Serialize and Deserialize BST](https://tinyurl.com/rx9rn3l)** | [Python](https://tinyurl.com/wu6rdaw/449_Serialize_and_Deserialize_BST.py), [Swift](https://tinyurl.com/wuja3c4/449_Serialize_and_Deserialize_BST.swift)| [Art 1](https://tinyurl.com/t6e2b97) | Medium | --- |
447447
|13| **[1008. Construct Binary Search Tree from Preorder Traversal](https://tinyurl.com/y6less2m)** | [Python](https://tinyurl.com/wu6rdaw/1008_Construct_Binary_Search_Tree_from_Preorder_Traversal.py), [Swift](https://tinyurl.com/wuja3c4/1008_Construct_Binary_Search_Tree_from_Preorder_Traversal.swift)| [Art 1](https://tinyurl.com/y9mondek), [Art 2](https://tinyurl.com/y8byt732), [Art 3](https://tinyurl.com/yaq7w2jt), [Art 4](https://tinyurl.com/ybwtzpzo) | Medium | --- |
448448
|14| **[653. Two Sum IV - Input is a BST](https://tinyurl.com/ydzdnawg)** | [Python](https://tinyurl.com/wu6rdaw/653_Two_Sum_IV_Input_is_a_BST.py), [Swift](https://tinyurl.com/wuja3c4/653_Two_Sum_IV_Input_is_a_BST.swift)| - | Easy | --- |
449+
|15| **[99. Recover Binary Search Tree](https://tinyurl.com/y9zxw8aj)** | [Python](https://tinyurl.com/wu6rdaw/99_Recover_Binary_Search_Tree.py), [Swift](https://tinyurl.com/wuja3c4/99_Recover_Binary_Search_Tree.swift)| - | Hard | **Very important, check again** |
449450

450451
</p>
451452
</details>
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode(object):
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.left = None
6+
# self.right = None
7+
8+
class Solution(object):
9+
def recoverTree(self, root):
10+
"""
11+
:type root: TreeNode
12+
:rtype: None Do not return anything, modify root in-place instead.
13+
"""
14+
stack = []
15+
x = y = predecessor = None # predecessor of the current node https://tinyurl.com/ycrzmfzg
16+
17+
while stack or root:
18+
while root:
19+
stack.append(root)
20+
root = root.left
21+
root = stack.pop()
22+
if predecessor and root.val < predecessor.val:
23+
y = root
24+
if not x:
25+
x = predecessor
26+
else:
27+
break
28+
predecessor = root
29+
root = root.right
30+
31+
x.val. y.val = y.val, x.val

0 commit comments

Comments
 (0)