• 98.Validate Binary Search Tree


    Given a binary tree, determine if it is a valid binary search tree (BST).

    Assume a BST is defined as follows:

    • The left subtree of a node contains only nodes with keys less than the node's key.
    • The right subtree of a node contains only nodes with keys greater than the node's key.
    • Both the left and right subtrees must also be binary search trees.

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

    思路1:看数组中序遍历是否按照从小到大的顺序。

    中序遍历采用非递归的实现方式,这样可以不用存储遍历的所有结果,只用保存前一个结果。

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isValidBST(TreeNode* root) {
            stack<TreeNode *> s;
            int before;
            bool once=true;
            while(!s.empty()||root){
                while(root){
                    s.push(root);
                    root=root->left;
                }
                TreeNode *cur=s.top();
                s.pop();
                if(once){
                    once=false;
                }
                else if(before>=cur->val)
                    return false;
                before=cur->val;
                root=cur->right;
            }
            return true;
        }
    };

    思路2:dfs,要保证树中的每一个节点都满足在左右边界范围之内。请注意,初始化时不能设置左右边界为INT_MIN,INT_MAX,因为给到的测试案例中有这两个数,为此不得不启用long类型,并设min=INT_MIN-1,max=INT_MAX+1。

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
         
         bool check(TreeNode *node, long min, long max)
         {
             if (!node)
                 return true;
             long val=node->val;
             return   val>min&&val<max&&check(node->left,min,val)&&check(node->right,val,max);    
            
         }
    public:
        bool isValidBST(TreeNode* root) {
            long min=INT_MIN;
            min--;
            long max=INT_MAX;
            max++;
            return check(root,min,max);
        }
    };
  • 相关阅读:
    springcloud 使用feign
    Could not resolve placeholder ‘xxx‘ in value “${xxx}“
    小程序中腾讯位置服务的使用/小程序中使用腾讯服务获取位置信息
    h5页面节假日置灰
    form表单提交入参唤起支付
    小程序中下拉框组件
    Android实践项目汇报(四)
    WORD表格数据运算技巧
    路由器桥接(WIFI无线中继)设置及摆放位置图解
    批处理设置IP地址
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5247748.html
Copyright © 2020-2023  润新知