首页 > 其他 > 详细

【leetcode】Validate Binary Search Tree(middle)

时间:2015-05-06 14:38:23      阅读:193      评论:0      收藏:0      [点我收藏+]

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.

 

思路:中序遍历。当前值要比之前的小。

bool isValidBST(TreeNode* root) {
        TreeNode * pPre = NULL;
        TreeNode * pCur = root;
        vector<TreeNode *> v;

        while(!v.empty() || NULL != pCur)
        {
            if(NULL != pCur)
            {
                v.push_back(pCur);
                pCur = pCur->left;
            }
            else
            {
                if(pPre != NULL && v.back()->val <= pPre->val)
                    return false;
                pPre = v.back();    
                v.pop_back();
                pCur = pPre->right;
            }
        }
        return true;
    }

 

大神递归版:注意,每次左子树的值范围在最小值和根值之间,右子树的范围在根植和最大值之间。

public class Solution {
    public boolean isValidBST(TreeNode root) {
        return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    public boolean isValidBST(TreeNode root, long minVal, long maxVal) {
        if (root == null) return true;
        if (root.val >= maxVal || root.val <= minVal) return false;
        return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal);
    }
}

 

【leetcode】Validate Binary Search Tree(middle)

原文:http://www.cnblogs.com/dplearning/p/4481565.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!