首页 > 其他 > 详细

leetcode 98 验证二叉搜索树

时间:2021-05-28 22:43:17      阅读:22      评论:0      收藏:0      [点我收藏+]

简介

使用中序遍历

code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> v;
    public void inOrder(TreeNode root){
        if(root == null) {
            return;
        }
        inOrder(root.left);
        v.add(root.val);
        inOrder(root.right);
    }
    public boolean isValidBST(TreeNode root) {
        v = new ArrayList<>();
        inOrder(root);
        if(v.size() == 0 || v.size() == 1){
            return true;
        }
        int tmp = v.get(0);
        for(int i=1; i<v.size(); i++){
            if(v.get(i) <= tmp){
                return false;
            }
            tmp = v.get(i);
        }
        return true;
    }
}

非递归方式实现的中序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode* root) {
        stack<TreeNode*> stack;
        long long inorder = (long long) INT_MIN - 1;
        while(!stack.empty() || root != nullptr){
            while(root != nullptr) {
                stack.push(root);
                root = root->left;
            }
            root = stack.top();
            stack.pop();
            // 如果中序遍历得到的节点的值小于等于前一个inorder, 说明不是二叉搜索树
            if(root->val <= inorder){
                return false;
            }
            inorder = root->val;
            root = root -> right;
        }
        return true;
    }
};

leetcode 98 验证二叉搜索树

原文:https://www.cnblogs.com/eat-too-much/p/14823822.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!