Skip to content

Commit 42642ff

Browse files
committed
Solution of Recovering Binary Search Tree
1 parent f9ab08d commit 42642ff

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

1-100q/99.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
'''
2+
Two elements of a binary search tree (BST) are swapped by mistake.
3+
4+
Recover the tree without changing its structure.
5+
6+
Example 1:
7+
8+
Input: [1,3,null,null,2]
9+
10+
1
11+
/
12+
3
13+
\
14+
2
15+
16+
Output: [3,1,null,null,2]
17+
18+
3
19+
/
20+
1
21+
\
22+
2
23+
'''
24+
# Definition for a binary tree node.
25+
# class TreeNode(object):
26+
# def __init__(self, x):
27+
# self.val = x
28+
# self.left = None
29+
# self.right = None
30+
31+
class Solution(object):
32+
def recoverTree(self, root):
33+
"""
34+
:type root: TreeNode
35+
:rtype: void Do not return anything, modify root in-place instead.
36+
"""
37+
38+
first, second, prev = None, None, None
39+
def inorder(root):
40+
if root:
41+
inorder(root.left)
42+
if prev is not None and root.val < prev.val:
43+
if first is None:
44+
first = root
45+
else:
46+
second = root
47+
prev = root
48+
inorder(root.right)
49+
50+
51+
inorder(root)
52+
if first and second:
53+
first.val, second.val = second.val, first.val

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ Python solution of problems from [LeetCode](https://leetcode.com/).
9696
##### [Problems 1-100](./1-100q/)
9797
| # | Title | Solution | Difficulty |
9898
|---| ----- | -------- | ---------- |
99+
|99|[Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree)|[Python](./1-100q/99.py)|Hard|
99100
|98|[Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)| [Python](./1-100q/98.py)|Medium|
100101
|97|[Interleaving String](https://leetcode.com/problems/interleaving-string/)| [Python](./1-100q/97.py)|Hard|
101102
|95|[Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/)| [Python](./1-100q/95.py)|Medium|

0 commit comments

Comments
 (0)