题目:

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的中序遍历结果是个升序的数组

 

相关文章:

  • 2021-06-05
  • 2022-01-16
  • 2021-11-19
  • 2021-12-11
  • 2022-12-23
猜你喜欢
  • 2022-01-28
  • 2021-11-29
  • 2022-02-24
  • 2021-09-27
  • 2021-07-30
  • 2022-01-09
相关资源
相似解决方案