zoukankan      html  css  js  c++  java
  • 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.

    思路

    递归,对于每个根节点,判断左右子节点是否在规定的大小区间内,然后再判断两个子树是否是合法的。

     1     bool isValid(TreeNode *root, int min, int max){
     2         if(root == NULL)
     3             return true;
     4         if(root->val <= min || root->val >= max)
     5             return false;
     6         return isValid(root->left, min, root->val)&&isValid(root->right, root->val, max);
     7     }
     8     bool isValidBST(TreeNode *root) {
     9         // Note: The Solution object is instantiated only once and is reused by each test case.
    10         if(root == NULL)
    11             return true;
    12         return isValid(root->left, INT_MIN, root->val)&&isValid(root->right, root->val, INT_MAX);
    13     }
  • 相关阅读:
    image对象
    Frame/IFrame 对象
    Form 对象
    JavaScript 对象 实例
    button对象
    正则介绍以及多种使用方法
    js /jquery停止事件冒泡和阻止浏览器默认事件
    一些兼容性的知识
    面试题总结
    事件
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3372860.html
Copyright © 2011-2022 走看看