您的位置:首页 > 其它

[LeetCode] Validate Binary Search Tree

2012-11-16 09:23 387 查看
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.

OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

1
/ \
2   3
/
4
\
5

The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.

递归判断,递归时传入两个参数,一个是左界,一个是右界,节点的值必须在两个界的中间,同时在判断做子树和右子树时更新左右界。

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool check(TreeNode *node, int leftVal, int rightVal)
{
if (node == NULL)
return true;

return leftVal < node->val && node->val < rightVal && check(node->left, leftVal, node->val) &&
check(node->right, node->val, rightVal);
}

bool isValidBST(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return check(root, INT_MIN, INT_MAX);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: