tutorialcup
Search in a Binary Search Tree Leetcode Solution
In this problem, we are given a Binary Search Tree and an integer. We need to find the address of a node with value same as the given integer. As a check, we need to print the preorder traversal of the sub-tree that has this node as root. If there is no value same as the given integer in the tree, we need to return NULL, i.e, an empty tree.
Example
2
/
1 3
4
Target Value = 3
3 4
5
/
1 10
Target Value = 4
Empty BST
Explanation #1
BST contains a node with value 3, so we return its sub-tree and print its preorder traversal.
Explanation #2
BST doesn't contain any node with value 4, so we return NULL and print "Empty BST".
Approach(Recursive)
Let us think of how a problem depends on subproblem in this case. Let say our function returns the address of node with target value, if found. We start from the root of the tree. If this node is NULL, it is obvious we have reached the end of the binary search tree and hence there is no node with target value. So, we return NULL. Similarly, we the node value is equal to the target value, we return this node. Otherwise, we know that the target-valued node will either be in left subtree or right subtree of current root. We can decide the direction(left or right) by comparing root.value and target value. So, we call the same recursive function with root as root.left or root.right.
www.tutorialcup.com/leetcode-solutions/search-in-a-binary...
Search in a Binary Search Tree Leetcode Solution
In this problem, we are given a Binary Search Tree and an integer. We need to find the address of a node with value same as the given integer. As a check, we need to print the preorder traversal of the sub-tree that has this node as root. If there is no value same as the given integer in the tree, we need to return NULL, i.e, an empty tree.
Example
2
/
1 3
4
Target Value = 3
3 4
5
/
1 10
Target Value = 4
Empty BST
Explanation #1
BST contains a node with value 3, so we return its sub-tree and print its preorder traversal.
Explanation #2
BST doesn't contain any node with value 4, so we return NULL and print "Empty BST".
Approach(Recursive)
Let us think of how a problem depends on subproblem in this case. Let say our function returns the address of node with target value, if found. We start from the root of the tree. If this node is NULL, it is obvious we have reached the end of the binary search tree and hence there is no node with target value. So, we return NULL. Similarly, we the node value is equal to the target value, we return this node. Otherwise, we know that the target-valued node will either be in left subtree or right subtree of current root. We can decide the direction(left or right) by comparing root.value and target value. So, we call the same recursive function with root as root.left or root.right.
www.tutorialcup.com/leetcode-solutions/search-in-a-binary...