题目描述:
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:
class Solution
{
public:
TreeNode *pre = NULL;
bool res = true;
bool isValidBST(TreeNode* root)
{
if(root == NULL)
return res;
help(root);
return res;
}
void help(TreeNode *node)
{
if(node == NULL)
return;
help(node->left);
if(pre == NULL)
{
pre = node;
}
else
{
if(pre->val >= node->val)
{
res = false;
return;
}
pre = node;
}
help(node->right);
}
};
解题思路:
class Solution {
public:
bool isSymmetric(TreeNode* root)
{
if(root == NULL)
return true;
queue<TreeNode*> sta;
sta.push(root->left);
sta.push(root->right);
while(!sta.empty())
{
TreeNode *t1 = sta.front();
sta.pop();
TreeNode *t2 = sta.front();
sta.pop();
if(t1 == NULL && t2 == NULL)
continue;
if(t1 == NULL || t2 == NULL)
return false;
if(t1->val != t2->val)
return false;
sta.push(t1->left);
sta.push(t2->right);
sta.push(t1->right);
sta.push(t2->left);
}
return true;
}
};
解题思路:
每次取出对称的两个点进行比较
这两个点后续的点入队列的话也要注意是按照对称的形式入队列。利用了队列先进先出的性质。