Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

RECOVER THE BST

TEST TIME ON THE CELEBRITY PROBLEM

URL:
RECOVER THE BST

EXPLANATION

Recovering a Binary Search Tree (BST) typically involves restoring its

structure when it's been corrupted. This can be done by identifying and

correcting two misplaced nodes that violate the BST property, usually by

swapping their values, ensuring the tree regains its sorted order.
RECOVER THE BST

EXPLANATION
1.Binary Tree Structure: A BST is a binary tree, meaning each node has at

most two children: a left child and a right child.

2.Ordering Property: In a BST, for any given node:

All nodes in its left subtree have values less than the node's value.

All nodes in its right subtree have values greater than the node's

value.

3.Unique Values: Typically, in a standard BST, each node has a unique value.

There are variations, such as Binary Search Trees with Duplicates, where

nodes can have identical values.


RECOVER THE BST

EXPLANATION In this example:


• The root node has a value of 10.
10
• The left subtree of the root contains nodes with values less than
/ \
10 (5, 3, and 8).
5 15 • The right subtree of the root contains nodes with values greater
than 10 (15 and 20).
/ \ \
• This tree follows the ordering property of a BST. For instance:
3 8 20
• All nodes in the left subtree of the root (5, 3, and 8) have
values less than 10.
• All nodes in the right subtree of the root (15 and 20) have values
greater than 10.
RECOVER THE BST

APPROACHES

1. Inorder Traversal and Two-Pointer Approach:

2. Morris Traversal (Constant Space):


RECOVER THE BST

APPROACHES 1. Inorder Traversal and Two-Pointer Approach:

This method involves performing an inorder traversal of a binary search tree

(BST) using two pointers. It identifies two incorrectly placed nodes during

traversal and swaps their values to restore the BST property, achieving a time

complexity of O(n) and space complexity of O(h), where h is the height of the

tree.
RECOVER THE BST

APPROACHES 1. Inorder Traversal and Two-Pointer Approach:


Sample Input Explanation:

3 In this sample, we have a binary search tree (BST) that is

/ \ initially incorrect. The tree is represented as follows:

1 4 • The root node has a value of 3.

/ • The left child of the root has a value of 1.

2 • The right child of the root has a value of 4.

Output • The right child of the root's right child has a value of

Inorder Traversal of Recovered BST: 2.

1 2 3 4 This tree violates the BST property because some of its nodes

are not in the correct order. Specifically, the node with

value 2 should be on the left side of the node with value 3


RECOVER THE BST

class TreeNode { // Perform inorder traversal


int val; inorder(root);
TreeNode left;
TreeNode right; // Swap the values of the two
incorrectly placed nodes
TreeNode(int val) { int temp =
this.val = val; firstIncorrectNode.val;
} firstIncorrectNode.val =
} secondIncorrectNode.val;
secondIncorrectNode.val = temp;
public class Main { }
TreeNode firstIncorrectNode = null;
TreeNode secondIncorrectNode = null; private void inorder(TreeNode node)
TreeNode prevNode = new {
TreeNode(Integer.MIN_VALUE); if (node == null) return;

public void recoverTree(TreeNode inorder(node.left);


root) {
// Check for incorrectly placed
nodes
RECOVER THE BST

if (firstIncorrectNode == null && root.right.left = new TreeNode(2);


prevNode.val >= node.val) { Main solution = new Main();
firstIncorrectNode = solution.recoverTree(root);
prevNode; // Print the corrected BST
} System.out.println("Inorder
if (firstIncorrectNode != null Traversal of Recovered BST:");
&& prevNode.val >= node.val) { printInorder(root);
secondIncorrectNode = node; }
} // Helper function to print the
prevNode = node; inorder traversal of a tree
inorder(node.right); private static void
} printInorder(TreeNode node) {
public static void main(String[] if (node == null) return;
args) { printInorder(node.left);
// Create a sample binary search System.out.print(node.val + "
tree with incorrect nodes ");
TreeNode root = new TreeNode(3); printInorder(node.right);
root.left = new TreeNode(1); }
root.right = new TreeNode(4); }
RECOVER THE BST

TIME AND SPACE COMPLEXITY

Time Complexity: O(n), where n is the number of nodes in the BST, as it

performs an inorder traversal of the entire tree.

Space Complexity: O(h), where h is the height of the BST. In the worst case,

when the BST is skewed, it can be O(n), but in a balanced BST, it's O(log n).
RECOVER THE BST

APPROACHES 2.Morris Traversal (Constant Space):

Morris Traversal is an efficient technique to perform an inorder traversal of a

BST with constant space usage. It identifies incorrectly placed nodes while

traversing, swapping their values after traversal, and also achieves a time

complexity of O(n), making it memory-efficient for large trees.


RECOVER THE BST

class TreeNode { while (current != null) {


int val; if (current.left == null) {
TreeNode left; // Process current node
TreeNode right; if (prevNode != null &&
prevNode.val >= current.val) {
TreeNode(int val) { if
this.val = val; (firstIncorrectNode == null) {
}
} firstIncorrectNode = prevNode;
}
public class Main { secondIncorrectNode
TreeNode firstIncorrectNode = null; = current;
TreeNode secondIncorrectNode = null; }
TreeNode prevNode = null; prevNode = current;

public void recoverTree(TreeNode current = current.right;


root) { } else {
TreeNode current = root; // Find the inorder
TreeNode temp; predecessor
RECOVER THE BST

temp = current.left; if (prevNode != null && prevNode.val >=


while (temp.right != current.val) {
null && temp.right != current) { if
temp = temp.right; (firstIncorrectNode == null) {
}
firstIncorrectNode = prevNode;
if (temp.right == null) }
{
// Set the right secondIncorrectNode = current;
pointer to enable returning to the }
current node prevNode = current;
temp.right =
current; current =
current = current.right;
current.left; }
} else { }
// Restore the right }
pointer and process current node
temp.right = null; // Swap the values of the two
incorrectly placed nodes
RECOVER THE BST

int tempVal = firstIncorrectNode.val; Main solution = new Main();


firstIncorrectNode.val = solution.recoverTree(root);
secondIncorrectNode.val; // Print the inorder traversal
secondIncorrectNode.val = of the recovered BST
tempVal; System.out.println("Inorder
} Traversal of Recovered BST:");
printInorder(root);
public static void main(String[] }
args) { // Helper function to print the
// Create a sample binary search inorder traversal of a tree
tree with 5 numbers (incorrect order) private static void
TreeNode root = new TreeNode(3); printInorder(TreeNode node) {
root.left = new TreeNode(1); if (node == null) return;
root.right = new TreeNode(5);
root.right.left = new printInorder(node.left);
TreeNode(2); System.out.print(node.val + "
root.right.right = new ");
TreeNode(4); printInorder(node.right);
}
}
RECOVER THE BST

TIME AND SPACE COMPLEXITY

Time Complexity: O(n), where n is the number of nodes in the BST, as it

performs an inorder traversal of the entire tree.

Space Complexity: O(1) because it uses constant space, making it

memory-efficient.
RECOVER THE BST

COMPARISION

• Morris Traversal is preferred when space efficiency is critical, as it uses

constant space.

• The Two-Pointer Approach may have higher space complexity, especially in

skewed trees.

• Both methods have the same time complexity of O(n) for traversal.

• Overall, Morris Traversal is generally the better choice when memory

constraints are important.


INTERVIEW QUESTIONS

1. What is the purpose of recovering a BST in an interview context?

Answer: The goal of recovering a BST in an interview is to demonstrate

your understanding of algorithms and data structures. It tests your

ability to identify and correct issues in a binary search tree, which is a

common problem-solving skill.


INTERVIEW QUESTIONS

2. Can you explain a common scenario where a BST needs to be recovered?

Answer: A common scenario is when two nodes in a BST are swapped or when

their values are incorrect. Recovering the BST means restoring the tree's

properties so that it becomes a valid BST.


INTERVIEW QUESTIONS

3. What are the primary approaches for recovering a corrupted BST, and how
do they work?

Answer: Two primary approaches are the Inorder Traversal with Two-Pointer

Approach and Morris Traversal. They both identify incorrectly placed nodes

by traversing the tree in a specific way and then swap their values to

recover the BST.


INTERVIEW QUESTIONS

4. Explain the concept of Morris Traversal in the context of recovering a


BST.

Answer: Morris Traversal is an efficient method for recovering a BST

with constant space usage. It uses threaded binary trees to traverse the

tree without using additional space. It identifies incorrectly placed

nodes during traversal and corrects them.


/ethnuscodemithra Ethnus Codemithra /ethnus /code_mithra

https://learn.codemithra.com

codemithra@ethnus.com +91 7815 095 095 +91 9019 921 340

You might also like