zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    需求获取常见的方法是进行客户访谈,结合你的实践谈谈会遇到什么问题,你是怎么解决的?
    软件工程导论 习题五
    软件工程导论 习题四
    软件工程导论 习题三
    软件工程导论 习题二(1.2.3.5)
    软件工程导论 习题一
    面向对象分析方法和面向过程分析方法的区别
    几大开发模型区别与联系
    项目总结
    关于需求
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14823822.html
Copyright © 2011-2022 走看看