题目:
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
题意解析:这道题目是给定一颗树,判断是否为二叉搜索树,我们都知道二叉搜索树中序遍历后是从小到大的一个序列,我们可以将其中序遍历输出,判断其是否为一个升序的序列即可,或者一边遍历一边判断,而一边遍历一边判断可大大节省时间,因此采用在遍历中判断的方法。
一种c++的实现如下:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include<iostream> #include<cstdio> #include<cstdlib> using namespace std; class Solution { public: bool first = true; int last_value; bool isValidBST(TreeNode* root) { if(root == NULL){ return true; } return isValidBST(root->left) && Comparison(root->val) &&isValidBST(root->right); } bool Comparison(int val) { if(first) { first = false; last_value = val; return true; } if(val <= last_value) return false; last_value = val; return true; } };