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;
          }
      }
  • 相关阅读:
    初识HTML5
    java_类的有参方法
    示例:人机猜拳(请各位大佬看下)
    java-类和对象(笔记)
    Redis设计与实现——多机数据库的实现
    Redis设计与实现——独立功能的实现
    mina
    GUAVA-cache实现
    GUAVA-ListenableFuture实现回调
    Netty多协议开发
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4652700.html
Copyright © 2011-2022 走看看