问题描述:
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
执行结果:
代码描述:
思路:中序遍历(迭代遍历),然后判断左侧小于右侧。
/**
* 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:
//vector<int> temp;
bool isValidBST(TreeNode* root) {
if(root == NULL) return true;
else
{
vector<int> temp;
stack<TreeNode*> s;
TreeNode *p = root;
while(!s.empty() || p != NULL)
{
if(p != NULL)
{
s.push(p);
p = p->left;
}
else
{
p = s.top();
s.pop();
temp.push_back(p->val);
p = p->right;
}
}
for(int i = 0; i < temp.size()-1; ++i)
{
if(temp[i] >= temp[i+1])
return false;
}
}
return true;
}
};
参考递归遍历。