Skip to content

Commit

Permalink
Solution of Recovering Binary Search Tree
Browse files Browse the repository at this point in the history
  • Loading branch information
Garvit244 committed Jun 13, 2018
1 parent f9ab08d commit 42642ff
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
53 changes: 53 additions & 0 deletions 1-100q/99.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
'''
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
Input: [1,3,null,null,2]
1
/
3
\
2
Output: [3,1,null,null,2]
3
/
1
\
2
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""

first, second, prev = None, None, None
def inorder(root):
if root:
inorder(root.left)
if prev is not None and root.val < prev.val:
if first is None:
first = root
else:
second = root
prev = root
inorder(root.right)


inorder(root)
if first and second:
first.val, second.val = second.val, first.val
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ Python solution of problems from [LeetCode](https://leetcode.com/).
##### [Problems 1-100](./1-100q/)
| # | Title | Solution | Difficulty |
|---| ----- | -------- | ---------- |
|99|[Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree)|[Python](./1-100q/99.py)|Hard|
|98|[Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)| [Python](./1-100q/98.py)|Medium|
|97|[Interleaving String](https://leetcode.com/problems/interleaving-string/)| [Python](./1-100q/97.py)|Hard|
|95|[Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/)| [Python](./1-100q/95.py)|Medium|
Expand Down

0 comments on commit 42642ff

Please sign in to comment.