Posts

Showing posts with the label Binary Search Tree

Validate Binary Search Tree

Image
Given the   root   of a binary tree,   determine if it is a valid binary search tree (BST) . A  valid BST  is defined as follows: The left subtree of a node contains only nodes with keys  less than  the node's key. The right subtree of a node contains only nodes with keys  greater than  the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [2,1,3] Output: true Example 2: Input: root = [5,1,4,null,null,3,6] Output: false Explanation: The root node's value is 5 but its right child's value is 4.   Constraints: The number of nodes in the tree is in the range  [1, 10 4 ] . -2 31  <= Node.val <= 2 31  - 1 Solution: /**  * Definition for a binary tree node.  * public class TreeNode {  *     int val;  *     TreeNode left;  *     TreeNode right;  *     TreeNode() {}  *     TreeNode(int val) { this.val =

Unique Binary Search Trees

Given n , how many structurally unique BST's (binary search trees) that store values 1 ...  n ? Example: Input: 3 Output: 5 Explanation: Given n = 3, there are a total of 5 unique BST's: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3   class Solution {     public int numTrees(int n) {          int countUniqueTrees[] = new int[n + 1];         countUniqueTrees[0] = 1;     countUniqueTrees[1] = 1;       for (int i = 2; i <= n; i++)      {         for (int j = 1; j <= i; j++)          {             countUniqueTrees[i] = countUniqueTrees[i] + (countUniqueTrees[i - j] *                               countUniqueTrees[j - 1]);         }     }       return countUniqueTrees[n];     } } Try it on Leetcode The idea behind solving this problem is , for all possible values of i, consider i as root, such that 1....i-1 will com

Construct Binary Search Tree from Preorder Traversal

Image
Return the root node of a binary search tree that matches the given preorder traversal. [Form Binary Search Tree from Preorder Traversal] (Recall that a binary search tree is a binary tree where for every node , any descendant of node.left has a value <   node.val , and any descendant of node.right has a value >   node.val .  Also recall that a preorder traversal displays the value of the  node first, then traverses node.left , then traverses node.right .) /**  * Definition for a binary tree node.  * public class TreeNode {  *     int val;  *     TreeNode left;  *     TreeNode right;  *     TreeNode(int x) { val = x; }  * }  */ class Solution {     public TreeNode bstFromPreorder(int[] preorder) {         if(preorder.length == 0){             return null;         }         TreeNode root = new TreeNode(preorder[0]);         for(int i = 1; i < preorder.length; i++){             constructBinarySearchTree(root, preorder[i]);             System.out.println(root.val