题目:
Validate 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.
思路:一种方法是,先判断左侧左子树是否为BST,再判断右子树是否为BST,如果都是,再判断左子树最大的是否小于根节点,右子树最小的是否大于根节点,如果都是,则为合法的BST,具体实现可用递归,可是这种方法的缺陷是递归的次数太多,时间复杂度太大。另一种时间复杂度合理的思路是把这这棵树按照中序遍历打印出来,看看是否从小到大,因为中序遍历从小到大等价于为BST,实现按照递归来做,递归次数合理,时间复杂度不会太大。
代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct Node {
int val;
Node * next;
Node(int x) : val(x), next(NULL){}
};
class Solution {
public:
Node * makeInorderList(TreeNode * root)
{
if(root==NULL)
{
return NULL;
}
if(root->left==NULL && root->right==NULL)
{
Node * list= new Node(root->val);
return list;
}
if(root->left!=NULL)
{
Node * list=makeInorderList(root->left);
Node * p=list;
while(p->next!=NULL)
{
p=p->next;
}
p->next=new Node(root->val);
if(root->right!=NULL)
{
p=p->next;
p->next=makeInorderList(root->right);
}
return list;
}else
{
Node * list=new Node(root->val);
if(root->right!=NULL)
{
list->next=makeInorderList(root->right);
}
return list;
}
}
bool isValidBST(TreeNode *root) {
if(root==NULL)
{
return true;
}
Node * list=makeInorderList(root);
Node * p=list;
if(p->next==NULL)
{
return true;
}
Node *q=p->next;
while(q!=NULL)
{
if(p->val>=q->val)
{
return false;
}
p=p->next;
q=q->next;
}
return true;
}
};