【LeetCode】98. 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.

提示:

这道题需要知道一个二叉搜索树的特性,就是一个二叉搜索数的中序遍历结果是一个严格单调递增序列。在知道了这个性质之后,就很好解了,这里我们给出非递归和递归两种解法。

代码:

非递归:

/**
* 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:
bool isValidBST(TreeNode* root) {
if (!root) {
return true;
}
inOrder(root);
for (int i = ; i < v.size(); ++i) {
if (v[i] <= v[i-]) {
return false;
}
}
return true;
} void inOrder(TreeNode* node) {
if (!node) {
return;
}
inOrder(node->left);
v.push_back(node->val);
inOrder(node->right);
} private:
vector<int> v;
};

用了一个额外的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:
bool isValidBST(TreeNode* root) {
TreeNode* pre = nullptr;
return isValidBST(root, pre);
} bool isValidBST(TreeNode *node, TreeNode*& pre) {
if (!node) {
return true;
}
if (!isValidBST(node->left, pre)) {
return false;
}
if (pre && node->val <= pre->val) {
return false;
}
pre = node;
return isValidBST(node->right, pre);
}
};

代码简单了很多,其实遍历的时候还是按照中序的思路来的,但是由于pre指针在函数间传递的过程当中指向的位置会发生改变,因此需要注意在函数参数那里需要将其写为指针的引用。

上一篇:LeetCode OJ 98. Validate Binary Search Tree


下一篇:(笔记)Mysql命令select from:查询表中的数据(记录)