问题描述
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
Example 1:
2
/
1 3
Input: [2,1,3]
Output: true
Example 2:
5
/
1 4
/
3 6
Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node’s value is 5 but its right child’s value is 4.
分析
这是一道判断二叉树是否为二叉搜索树的问题。
二叉搜索树的特点是:任一节点的左子树都要小于该节点右子树的值。
于是我们可以采用中序遍历的方法,如果是二叉搜索树,则满足按中序遍历的顺序遍历的每个节点的值为递增序列。所以我们中序遍历,并用一个vector来记录每个节点的值。最后遍历vector看是不是按照递增顺序排列。
/**
* 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:
void Inorder(TreeNode* node, vector<int>& v)
{
if(node->left) Inorder(node->left,v);
v.push_back(node->val);
if(node->right) Inorder(node->right,v);
return;
}
bool isValidBST(TreeNode* root) {
if(!root) return true;
vector<int> v;
Inorder(root, v);
for(int i = 0; i<v.size()-1; i++)
{
if(v[i]>=v[i+1]) return false;
}
return true;
}
};