您的位置:首页 > 编程语言 > C语言/C++

【C++】 LeetCode 98. Validate Binary Search Tree

2017-05-12 21:31 579 查看

题目:

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.

Example 1:

2
/ \
1   3

Binary tree 
[2,1,3]
,
return true.

Example 2:

1
/ \
2   3

Binary tree 
[1,2,3]
,
return false.



解析:

二叉搜索树的中序遍历是递增序列,故考虑采用中序遍历的方式,判断是否为递增序列。由于int型为4字节,考虑可能溢出,故采用long long类型


代码:

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool forward(long long &res,TreeNode* root)
{
if(root->left!=NULL)
{
if(!forward(res,root->left))
return false;
}
if(res>=root->val)return false;
res=(long long)root->val;

if(root->right!=NULL)
{
if(!forward(res,root->right))
return false;
}
return true;
}
bool isValidBST(TreeNode* root) {
if(root==NULL)return true;
TreeNode* node=root;
while(1)
{
if(node->left!=NULL)
node=node->left;
else
break;
}
long long res=(long long)(node->val)-1;
return forward(res,root);
}
};

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: