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
  • 相关阅读:
    eclipse 闪退原因
    Ansj分词的使用
    pycharm实现sublime的显示效果,很惊艳哦
    使用pycharm以及用pycharm句子切分调试
    安装pytorch0.4.0
    vim设置一个tab为4个空格,设置行号
    读取html文件,让其中的内容和notepad打开这个html的样子一样。
    把变量,比如矩阵的值存储到文件里面去
    xpath分析 html文件抽正文的过程
    quepy
  • 原文地址:https://www.cnblogs.com/freeneng/p/3205207.html
Copyright © 2011-2022 走看看