[leet code] 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.

===============

Analysis:

Basic idea is to validate all rules of BST for each node in the given binary tree.  Accordingly, for each node (current node), we compare it to all the nodes in its left sub-tree, and all the node in its right sub-tree.  If there is any node in in its left or right sub-trees vibrates the BST rule, return false.  Otherwise, further check current node's left child and right child.

Obviously, we need a recursive function to check all the nodes in given binary tree.  Besides, for compare current node with all the nodes in its left and right sub-trees, we need another recursive function.

One more thing need to be careful is to define the false condition while comparing current node to nodes in its left and right sub-trees.

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isValidBST(TreeNode root) {
        if(root == null) return true; // exit
        // compare current node with all nodes in its left sub-tree and right sub-tree (be careful!)
        if(!helper(root.val, root.left, true)||!helper(root.val, root.right, false)) return false;
        // current node validated
        return isValidBST(root.left) && isValidBST(root.right);
    }
    
    public boolean helper(int value, TreeNode node, boolean left){
        if(node == null) return true;
        if(left == true && node.val >= value) return false;
        if(left == false && node.val <= value) return false;
        return helper(value, node.left, left) && helper(value, node.right, left);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值