码迷,mamicode.com
首页 > 其他好文 > 详细

Jan 27 - Valid Binary Search Tree; DFS;

时间:2016-01-28 13:45:06      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

Using DFS to traverse the BST, when we look through the BST to a certain node, this node must have the following property to make sure the tree is a valid BST:

if current node is a left child of its parent, its value should smaller than its parent‘s value.

then its left child(if exists,), its value should smaller than its own. While its right child, if exists, the value should should be larger than current node‘s but smaller than the parent‘s

Similarly, we can find the property of a node which is a right child of its parent.

We use two long-type variable to record the MIN, MAX value in the remaining tree. When we goes into a left child of current, update the max to be current node‘s value, when we goes into a right child of current node, update the min to be current node‘s value. Basically the min and max value is related to the parent node‘s value. Initially we set  Min to be Integer.MIN_VALUE-1 and MAX to be Integer.MAX_VALUE +1, to make sure it works when we look into root‘s child nodes, here Using long data type to avoid over range of integer value.

Code:

/**
 * Definition for a binary tree node.
 * 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;
        long min = (long) (Integer.MIN_VALUE)-1;
        long max = (long) (Integer.MAX_VALUE)+1;
        return isValidLeftSubtree(root.left, root.val, min) && isValidRightSubtree(root.right, max, root.val);
        
    }
    public boolean isValidLeftSubtree(TreeNode node, long max, long min){
        if(node == null) return true;
        if(node.val >= max || node.val <= min) return false;
        return isValidLeftSubtree(node.left, node.val, min) && isValidRightSubtree(node.right, max, node.val);
    }
    
    public boolean isValidRightSubtree(TreeNode node, long max, long min){
        if(node == null) return true;
        if(node.val >= max || node.val <= min) return false;
        return isValidLeftSubtree(node.left, node.val, min) && isValidRightSubtree(node.right, max, node.val);
    }
}

 

Jan 27 - Valid Binary Search Tree; DFS;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5165795.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!