zoukankan      html  css  js  c++  java
  • [Leetcode 76] 98 Validate Binary Search Tree

    Problem:

    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.

    Analysis:

    Tree problem always related to its recursive property. Here to judge whether a binary tree is a binary search tree, the condition is as follows.

       root

      /   

    left     right

    left sub-tree's nodes' value should all less than the root's value

    right sub-tree's nodes' valu should all greater than the root's value

    And do it recursively. 

    For the left-subtree, the max value is root->val and for right-subtree, the min value is root->val

    Here the construction of initial max and min value is a little tricky by using the bit operation. 

    Code:

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     bool isValidBST(TreeNode *root) {
    13         // Start typing your C/C++ solution below
    14         // DO NOT write int main() function
    15         int max = (1<<31)-1;
    16         int min = (1<<31);
    17         
    18         return judge(root, max, min);
    19     } 
    20     
    21 private:
    22     bool judge(TreeNode *n, int max, int min) {
    23         if (n == NULL)
    24             return true;
    25             
    26         if (n->val < max && n->val > min)
    27             return judge(n->left, n->val, min) && judge(n->right, max, n->val);
    28         else
    29             return false;
    30     }
    31 };
    View Code
  • 相关阅读:
    Go语言环境配置 Sublime Text + GoSublime+ gocode + MarGo组合
    Java中string拼接,StringBuilder,StringBuffer和+
    java调优随记-java对象大小
    java调优随记-堆和栈
    java中一直说一个汉字使用两个字节,原来是不准确的
    kv存储对抗关系型数据库
    记一篇
    变态的静态资源缓存与更新
    git add shh public key
    hashmap 的最优访问
  • 原文地址:https://www.cnblogs.com/freeneng/p/3205207.html
Copyright © 2011-2022 走看看