• Validate Binary Search Tree


    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.

    思路:

      dfs

    我的代码:

    public class Solution {
        public boolean isValidBST(TreeNode root) {
            if(root == null)    return true;
            return helper(root, null, null); 
        }
        public boolean helper(TreeNode root, Integer min, Integer max)
        {
            if(root == null)    return true;
            Integer val = root.val;
            if(min != null && val.compareTo(min) <= 0)    return false;
            if(max != null && val.compareTo(max) >= 0)    return false;
            return helper(root.left, min, root.val) && helper(root.right, root.val, max);
         }
    }
    View Code

    学习之处:

    • 在helper传入参数的时候,此处只能用Integer对象不能用int,因为int需要初始化,如果min初始化为Integer.MIN_VALUE max初始化为Integer.MAX_VALUE不能排除root.val真的等于Integer.MIN_VALUE max或Integer.MAX_VALUE的corcase
    • 之前一直觉得Integer对象的存在没有太多的意义,这道题给了一个很好的应用,既然第一次不能初始化,那么我用Integer中的null正好可以代替第一次,真的是好机智啊!!
    • 该问题还可以用中序遍历解决,因为中序遍历要求是递增的顺序的,想想中序遍历的非递归解法,貌似有印象while(stack.isEmpty()||cur !=null),只是在那边再加一个pre就OK了。
  • 相关阅读:
    java web项目防止多用户重复登录解决方案
    通过Google浏览器Cookie文件获取cookie信息,80以上版本有效
    js实现json数据导出为Excel下载到本地
    golang 搭建web服务器
    typescript笔记
    canvas屏幕动画
    canvas鼠标特效
    博客皮肤分享
    HTML的背景色和背景图、图片
    HTML表格头部、主体、页脚
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4357996.html
Copyright © 2020-2023  润新知