LeetCode-Validate Binary Search Tree

川长思鸟来 2022-08-04 00:59 117阅读 0赞

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.

难度不大,关键是能用多种方法解决之。

可以先按其本身的定义来解决此题:左子树的所有节点小于此节点,右子树的所有节点都大于此节点。当然还需要两个辅助方法,我称之为树的工具类方法,求最大值和最小值。

  1. public boolean isValidBST(TreeNode root) {
  2. return root == null || (root.left == null ? true : root.val > max(root.left)) &&
  3. (root.right == null ? true : root.val < min(root.right)) &&
  4. isValidBST(root.left) &&
  5. isValidBST(root.right);
  6. }
  7. public int max(TreeNode root) {
  8. if (root == null) return Integer.MIN_VALUE;
  9. return Math.max(Math.max(max(root.left), max(root.right)), root.val);
  10. }
  11. public int min(TreeNode root) {
  12. if (root == null) return Integer.MAX_VALUE;
  13. return Math.min(Math.min(min(root.left), min(root.right)), root.val);
  14. }

第二种方式是稍微转变一下可知,中序遍历BST,得到的是排序序列,所以就有了如下方法:

  1. public boolean isValidBST(TreeNode root) {
  2. List<Integer> ret = new ArrayList<Integer>();
  3. dfs(root, ret);
  4. for (int i = 0; i < ret.size()-1; i++) {
  5. if (ret.get(i) >= ret.get(i+1)) return false;
  6. }
  7. return true;
  8. }
  9. private void dfs(TreeNode root, List<Integer> ret) {
  10. if (root == null) return;
  11. dfs(root.left, ret);
  12. ret.add(root.val);
  13. dfs(root.right, ret);
  14. }

从上述两种方法,都不止一次遍历。所以肯定要思考有没有遍历一次就可以得出结论的,上代码:

  1. private TreeNode pre = null;
  2. public boolean isValidBST(TreeNode root) {
  3. if (root == null)
  4. return true;
  5. if (!isValidBST(root.left))
  6. return false;
  7. if (prev != null && prev.val >= root.val) return false;
  8. prev = root;
  9. return isValidBST(root.right);
  10. }

在遍历的过程中,记录前驱节点,在与本节点比较即可判断。

在遍历过程中可以进行很多改造,也就是改造遍历可以得出很多高效的算法!!!最后一种方法值得回味。

发表评论

表情:
评论列表 (有 0 条评论,117人围观)

还没有评论,来说两句吧...

相关阅读