import org.junit.jupiter.api.Test;
import org.omg.CORBA.INTERNAL;
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.
错误解法,只判断了每一个小的子树是搜索二叉树,而忽略了整个 root 的情况
1 | public class ValidateBinarySearchTree { |
通过的代码就是使用的搜索二叉树的中序遍历,他的终须遍历的话刚好出来结果就是
左边的树必须小于右边的数,这样就能很轻松的判断出来是否合法
1 | public class ValidateBinarySearchTree { |
以及终须遍历衍生出来的新方法,也就是不使用一个 list 集合来存储前后之间的关系
1 | class ValidateBinarySearchTree2 { |