今天天气不是很好,刚刷的这道题,看似简单实则不简单,下面就和大家分享一下经验吧!
题目如下:
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.
题意分析:
给定一个二叉树,请判断其是否为二分搜索树。
方法一(递归法)
可以根据二分搜索树的性质:左节点值 < 根节点值 < 右节点值,来给当前节点值设置上下限,如果超过上下限则返回false,否则继续递归调用直到当前节点为NULL时返回true。
解题代码如下:
class Solution{
public:
bool isValidBST(TreeNode* root){
if (root == NULL) return true;
return isValidBST_son(root, LONG_MIN, LONG_MAX);
}
bool isValidBST_son(TreeNode* root, long mn, long mx){
if (root == NULL) return true;
if(root->val > LONG_MAX && root->val < LONG_MIN) return false;
return isValidBST_son(root->left, mn, root->val) && isValidBST_son(root->right, root->val, mx);
}
};
提交后的结果如下:
方法二(中序遍历法)
对二分搜索树进行中序遍历得到的就是从小到大排序好的数组,所以可以先对二分搜索树进行中序遍历,然后再检测遍历后的结果是否有序即可。
解题代码如下:
class Solution{
public:
bool isValidBST(TreeNode* root){
if(root==NULL) return true;
vector<int> res;
InOrder(root, res);
for (int i = 0; i < res.size()-1; i++) {
if(res[i] >= res[i+1]) return false;
}
return true;
}
void InOrder(TreeNode* root, vector<int>& res){
if (root == NULL) return;
InOrder(root->left, res);
res.push_back(root->val);
InOrder(root->right, res);
}
};
提交后的结果如下:
日积月累,与君共进,增增小结,未完待续。