Wednesday, March 20, 2013
Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a 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.
make an inorder traversal, if the value is increasing, it is a BST.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private TreeNode pre;
private boolean ret;
void inorder(TreeNode root){
if(ret == false) return;
if(root==null) return;
inorder(root.left);
if(pre == null){ pre = root;}
else{
if(pre.val >= root.val){
ret = false;
return;
}
pre = root;
}
if(ret) inorder(root.right);
}
public boolean isValidBST(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
pre = null;
ret = true;
inorder(root);
return ret;
}
}
Subscribe to:
Post Comments (Atom)
Manacher's Longest Palindromic Substring Algorithm
http://manacher-viz.s3-website-us-east-1.amazonaws.com/#/
-
Suppose a bus is running on a loop route. It takes 10 mins for the bus to finish the route. If a guy arrives at a bus stop at uniformly rand...
-
Question: You are playing a card game with me. Suppose I shuffle a deck of 52 cards, then I show you the card one by one to you from top t...
-
Move Objects There are N objects kept in a row. The ith object is at position x_i. You want to partition them into K groups. You want ...
No comments:
Post a Comment