zoukankan      html  css  js  c++  java
  • [leedcode 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.
      /**
       * Definition for a binary tree node.
       * public class TreeNode {
       *     int val;
       *     TreeNode left;
       *     TreeNode right;
       *     TreeNode(int x) { val = x; }
       * }
       */
      public class Solution {
          public boolean isValidBST(TreeNode root) {
              //[2147483647]
              //注意,因为root的val是int型的,其可能为最大值或最小值,因此一开始的设置最大或最小要使用long型,注意函数参数的类型
              //本题非常巧妙使用最大值和最小值限制根节点的范围。最关键是对isvalid的正确定义,代表root的值是否在min和max中间
              
              //本题另一个解法是:将二叉树中序遍历,然后检测是否是递增数组
              return isvalid(root,(long)Integer.MIN_VALUE-1,(long)Integer.MAX_VALUE+1);
          }
          public boolean isvalid(TreeNode root,long min,long max){
              if(root==null){
                  return true;
              }
              long val=(long)root.val;
              if(val>min&&val<max){
                  return isvalid(root.left,min,val)&&isvalid(root.right,val,max);
              }else return false;
          }
      }
  • 相关阅读:
    linux 环境变量
    php 守护进程类
    PHP 操作 进程时相关 信号的具体含义
    mongodb 的注意点
    安装了包,pycharm却提示找不到包
    php7下 xhprof安装与使用
    mysql 大数据 查询方面的测试
    mysql 分页测试,
    jmeter 使用
    初步jmeter安装与使用
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4652700.html
Copyright © 2011-2022 走看看