LeetCode: Validata Binary Search Tree

时间:2022-09-06 20:05:59

LeetCode: Validata Binary Search Tree

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.

地址:https://oj.leetcode.com/problems/validate-binary-search-tree/

算法:中序遍历,看看遍历到的节点值是否递增。代码:

 /**
* 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 isValidBST(TreeNode *root) {
if(!root) return true;
stack<TreeNode*> stk;
TreeNode *p = root;
while(p){
stk.push(p);
p = p->left;
}
TreeNode *pre = NULL;
p = NULL;
while(!stk.empty()){
pre = p;
p = stk.top();
stk.pop();
if(pre && p->val <= pre->val){
return false;
}
if(p->right){
TreeNode *q = p->right;
while(q){
stk.push(q);
q = q->left;
}
}
}
return true;
}
};