• 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
  • 相关阅读:
    iOS Xcode8的适配
    iOS从生成证书到打包上架-02(详细2016-10最新)
    iOS从生成证书到打包上架-01(详细2016-10最新)
    PHP读取CSV文件
    magento批量导入评论加星
    magento调用static block
    Magento Block的几种调用方式
    JFinal项目中获取根目录
    清除UTF-8编码文件前端的DOM
    PhpStorm注册码(2,3,4,5)通用
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14823822.html
Copyright © 2020-2023  润新知