• 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.

    Example 1:

        2
       / 
      1   3
    
    Binary tree [2,1,3], return true.

    Example 2:

        1
       / 
      2   3
    
    Binary tree [1,2,3], return false.
     
     
     
    利用中序遍历,因为中序遍历的结果就是从小到大排好序的结果,如果是二叉搜索树的话。
     1 class Solution {
     2     public boolean isValidBST(TreeNode root) {
     3         if(root==null) return true;
     4         TreeNode cur = root;
     5         TreeNode pre = null;
     6         Stack<TreeNode> stack  = new Stack<TreeNode>();
     7         while(cur!=null || !stack.isEmpty()){
     8             while(cur!=null){
     9             stack.push(cur);
    10             cur = cur.left;
    11             }
    12             cur = stack.pop();
    13             if(pre!=null && pre.val>=cur.val) return false;
    14             pre =cur;
    15             cur=cur.right;
    16         }
    17         return true;
    18         
    19     }
    20   
    21 }
     
     
    利用递归,需要将最大值最小值传下去。
     1 class Solution {
     2     public boolean isValidBST(TreeNode root) {
     3         return test(root,Long.MIN_VALUE,Long.MAX_VALUE); 
     4     }
     5     private boolean test(TreeNode root,long min,long max){
     6         if(root==null) return true;
     7         if(root.val>=max ||root.val<=min) return false;
     8         return test(root.left,min,root.val) && test(root.right,root.val,max);
     9     }
    10 }
  • 相关阅读:
    动态创建html内容时所用的W3C DOM属性和方法
    CSS强制英文、中文换行与不换行 强制英文换行
    aspose.words .net 导出word表
    nodejs -数据分页ejs-分页控件
    mysql模块简单实用操作-----nodejs
    coffeeScript命令
    命令
    用node 开发简易爬虫
    电脑不支持VT-X问题解决
    hibernate 使用sql server的存储过程时没有返回值
  • 原文地址:https://www.cnblogs.com/zle1992/p/8342778.html
Copyright © 2020-2023  润新知