leetcode 98 验证二叉搜索树

简介

使用中序遍历

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;
    }
};
Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14823822.html