`
cozilla
  • 浏览: 89433 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

[LeetCode] Validate Binary Search Tree

 
阅读更多

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.

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

 

 

class Solution {
public:
    bool isValidBST(TreeNode *root) {
         return check(root, -(1<<30), 1<<30);
    }
    
    bool check(TreeNode* cur, int min_num ,int max_num) {
        if (cur == NULL) return true;
        if (cur->val > min_num && cur->val < max_num 
            && check(cur->left, min_num, cur->val)
            && check(cur->right, cur->val, max_num))
            return true;
        else return false;
    }
};

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics