vector<int> inorderTraversal(TreeNode *root) {
vector<TreeNode*> pre_node;
vector<int> val;
if (root == NULL)
{
return val;
}
pre_node.push_back(root);
while(!pre_node.empty())
{
TreeNode* cur_node = pre_node.back();
TreeNode* left_leaf = NULL;
TreeNode* right_leaf = NULL;
if(cur_node != NULL)
{
left_leaf = cur_node->left;
right_leaf = cur_node->right;
}
if(left_leaf != NULL)
{
pre_node.push_back(left_leaf);
}
else
{
val.push_back(cur_node->val);
pre_node.pop_back();
if(right_leaf != NULL)
{
pre_node.push_back(right_leaf);
}
else
{
while(!pre_node.empty())
{
cur_node = pre_node.back();
val.push_back(cur_node->val);
pre_node.pop_back();
if(cur_node->right != NULL)
{
pre_node.push_back(cur_node->right);
break;
}
}
}
}
}
return val;
}
bool isValidBST(TreeNode *root) {
if (root == NULL)
{
return true;
}
vector<int> inorderVals = inorderTraversal(root);
int lastVal = inorderVals[0];
for (int i = 1; i < inorderVals.size(); i++)
{
if (inorderVals[i] <= lastVal)
{
return false;
}
lastVal = inorderVals[i];
}
return true;
}
先中序遍历,再判断遍历结果是否单调递增
[LeetCode] Validate Binary Search Tree
最新推荐文章于 2020-10-15 09:59:45 发布