【leetcode】Validate Binary Search Tree(middle)

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);

    }

}

 

你可能感兴趣的:(Binary search)