zoukankan      html  css  js  c++  java
  • LeetCode :: Validate Binary Search Tree[具体分析]


    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.
    回想一下BST的定义,任一节点的子孙分别递归满足。左子孙小于该节点,右子孙大于该节点。仅仅要推断这个就OK了;
    一个主意点:在递归程序里面。仅推断一个节点大于左儿子小于右儿子是不够的,这样对于左儿子的右儿子以及右儿子的左儿子的
    错误推断不到,因此须要将节点值变为边界值,递归下传;
    代码例如以下:
    class Solution {
    public:
        bool isValidBST(TreeNode *root) {
            return check(root, INT_MIN, INT_MAX);
        }
        
    private:
        bool check(TreeNode *root, int left, int right){
            if(root == NULL)
                return true;
            return (root->val > left) && (root->val < right) 
                   && check(root->left, left, root->val) &&check(root->right, root->val, right); 
        }//这里的左儿子的左界用上面传下来的,右界用节点值,右儿子镜面对称
    };

    PS:依照注意点提到的思路写的错误代码
    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isValidBST(TreeNode *root) {
            if (root == NULL)
                return true;
                
            bool bleft = true, bright = true;
            if (root->left != NULL){
                if (root->val > root->left->val){    //注意这里检验以及递归是不能保证根节点大于左边全部的。矛盾在于,左儿子的右儿子,以及右儿子的左儿子。
                    bleft = isValidBST(root->left);
                }
                else{
                    return false;
                }
            }
            
            if (root->right != NULL){
                if (root->val < root->right->val){
                    bright = isValidBST(root->right);
                }
                else{
                    return false;
                }
            }
            return bleft && bright;
        }
    };



    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    UVA 1025 A Spy in the Metro DP水题
    ZOJ 3814 Sawtooth Puzzle BFS
    ZOJ 3816 Generalized Palindromic Number
    UVA 10859 Placing Lampposts 树形DP
    UVA 11825 Hackers' Crackdown 状压DP
    POJ 2887 Big String 线段树 离线处理
    POJ 1635 Subway tree systems Hash法判断有根树是否同构
    BZOJ 3110 k大数查询 & 树套树
    sdoi 2009 & 状态压缩
    来自于2016.2.24的flag
  • 原文地址:https://www.cnblogs.com/yxwkf/p/4636035.html
Copyright © 2011-2022 走看看