[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.
这个也算是基础题吧,目前经历过的所有关于树的问题,归根结底都是一个遍历的问题,BST是一个中序遍历的有序。最直接的想法很简单,直接中序遍历,储存每个值到一个list,然后遍历list检查是否有序。其实还好,2个O(N)还是O(N),还有额外空间开销。
比较广泛的解法是下面这样:
public class Solution { public boolean isValidBST(TreeNode root) { return isValidBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } private boolean isValidBST(TreeNode root, int min, int max) { if (root == null) return true; if (root.val > min && root.val < max && isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max)) { return true; } else { return false; } } }
这个解法是参考stackoverflow做出的,自己写的代码没有这么优雅,但是基本思路一致。遍历的过程中可以实时检查当前node的值。所以引入变量才是王道。
什么时候要研究一下,到底怎么样把递归转为循环,引入一个stack?