zoukankan      html  css  js  c++  java
  • 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了。
  • 相关阅读:
    第 9 章 类
    导入模块
    第 8 章 函数
    第七章 用户输入和while语句
    第六章 字典
    测试经理/组长职责
    测试的发展之路
    【转】测试流程
    一个网页通用的测试用例(借鉴他人的保存,加注释)
    QTP自动化测试框架简述
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4357996.html
Copyright © 2011-2022 走看看