1、题目描述
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/
1 3
输出: true
示例 2:
输入:
5
/
1 4
/
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
2、我的代码
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(root == NULL)
return true;
stack<TreeNode*> nodeStack;
int prevalue = INT_MIN;
while(!nodeStack.empty() || root != NULL){
if(root != NULL){
nodeStack.push(root);
root = root->left;
}else{
root = nodeStack.top();
if(prevalue < root->val){
//prevalue = root->val;
}else{
return false;
}
prevalue = root->val;
nodeStack.pop();
root = root->right;
}
}
return true;
}
};
3、网上好的解法
class Solution {
public boolean isValidBST(TreeNode root) {
return core(root, null, null);
}
private boolean core(TreeNode node, TreeNode min, TreeNode max) {
if(node == null) return true;
if(min != null && node.val <= min.val) return false;
if(max != null && node.val >= max.val) return false;
return core(node.left, min, node) && core(node.right, node, max);
}
}
4、自己可以改进的地方
自己写的这个逻辑,处理
[-2,1,4,7,4,8,3,6,4,8]时返回false,leetcode正确结果是true,
5、优化代码至简无可简
class Solution {
public:
bool core(TreeNode* root, int low, int high){
if(root == NULL) return true;
if(root->val <= low) return false;
if(root->val >= high) return false;
return core(root->left,low,root->val) && core(root->right,root->val,high);
}
bool isValidBST(TreeNode* root) {
return core(root,INT_MIN,INT_MAX);
}
};
6、我的思考
二叉树相关的算法是比较典型的考察点,相关的处理思路需要反复比较全面掌握