题目来源:https://leetcode.cn/problems/validate-binary-search-tree/description/
C++题解1:中序遍历,递归法。获取数组,如果是递增则返回true,否则返回false。
class Solution {
public:void zhongxu(TreeNode* node, vector<int>& sto){if(!node) return;zhongxu(node->left, sto);sto.push_back(node->val);zhongxu(node->right, sto); return; }bool isValidBST(TreeNode* root) {if(!root) return true;vector<int> sto;zhongxu(root, sto);int len = sto.size();for(int i = 1; i < len; i++){if(sto[i] <= sto[i-1]) return false;}return true;}
};
C++题解2:中序遍历,递归法。不断更新最大值,初始化为最左最下层的节点值,按照中序遍历可以更新为上一节点的值。
class Solution {
public:TreeNode* pre = NULL; // 用来记录前一个节点bool isValidBST(TreeNode* root) {if (root == NULL) return true;bool left = isValidBST(root->left);if (pre != NULL && pre->val >= root->val) return false;pre = root; // 记录前一个节点bool right = isValidBST(root->right);return left && right;}
};
C++题解3:迭代法。
class Solution {
public:bool isValidBST(TreeNode* root) {stack<TreeNode*> st;TreeNode* cur = root;TreeNode* pre = NULL; // 记录前一个节点while (cur != NULL || !st.empty()) {if (cur != NULL) {st.push(cur);cur = cur->left; // 左} else {cur = st.top(); // 中st.pop();if (pre != NULL && cur->val <= pre->val)return false;pre = cur; //保存前一个访问的结点cur = cur->right; // 右}}return true;}
};