zoukankan      html  css  js  c++  java
  • leetcode 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

    这道题我想了个解法,就是为每一棵树设置上下界,用递归的算法求解。

    然而报错,因为在设置上下限的时候,用Integer.max_value表示正无穷,Integer.min_value表示负无穷,

    然而在具体操作的时候,树中有可能就存在Integer.max_value或者Integer.min_value
    从而产生错误。

    百度了一下,有个很巧妙的解法

    即,对BST进行中序遍历,中序遍历的结果必然是升序的。

    这道题的解法告诉我们,BST的中序遍历结果是个升序的数组

  • 相关阅读:
    Unity3D 4.0 界面 基础 入门
    try catch finally 用法
    Mysql表引擎Innodb、MyIsam、Memory
    初步的kudu+impala vs dorisdb vs tidb
    mysql创建类似oracle的dblink
    jedis请求keys超时报错
    php 1223
    php 1214
    php 1216
    php 1222
  • 原文地址:https://www.cnblogs.com/elnino/p/5541495.html
Copyright © 2011-2022 走看看