Binary search trees are a special type of binary trees where the value in each node
is greater than any value stored in the left sub-tree,
and less than any value stored in the right sub-tree.
Write a function to find a value in the given binary search tree.
Starter Code
publicclassNode{
int val;
Node left;
Node right;
Node() { }
Node(int setVal) {
this.val = setVal;
}
Node(int setVal, Node setLeft, Node setRight) {
this.val = setVal;
this.left = left;
this.right = right;
}
}
public Node searchBST(Node root, int val){
// write your code here
}
That's all, folks!
Thanks for stopping by today. We hope you learned alot about how useful recursion is to solve tree problems.
Only a few more weeks to go! Hang in there everyone and enjoy the rest of your week.
Solution Section
Find the Height of Binary Tree - Solution
publicstaticintfindHeight(Node root){
if (root == null) {
return0;
}
int lHeight = findHeight(root.left);
int rHeight = findHeight(root.right);
if (lHeight > rHeight) {
return lHeight + 1;
} else {
return rHeight + 1;
}
}
Find the Sum of Left Leaves - Solution
publicintsumOfLeftLeaves(Node root){
if (root == null) {
return0;
}
return processSubtree(root, false);
}
privateintprocessSubtree(Node subtree, boolean isLeft){
// Base case: This is a leaf node.if (subtree.left == null && subtree.right == null) {
if (isLeft) {
return subtree.val;
} else {
return0;
}
}
// Recursive case: We need to add and return the results of the// left and right subtrees.int total = 0;
if (subtree.left != null) {
total += processSubtree(subtree.left, true);
}
if (subtree.right != null) {
total += processSubtree(subtree.right, false);
}
return total;
}
Find A Value in a Binary Search Tree - Solution
public Node searchBST(Node root, int val){
if (root == null || val == root.val) {
return root;
}
if (val < root.val) {
return searchBST(root.left, val);
} else {
return searchBST(root.right, val);
}
}