LeetCode98. 验证二叉搜索树
☆☆思路:中序遍历时,判断当前节点是否大于中序遍历的前一个节点,如果大于,满足BST,继续遍历;否则返回false。
技巧点:保存前一个节点 + 中序遍历
class Solution { TreeNode pre = null; public boolean isValidBST(TreeNode root) { if (root == null) return true; // 访问左子树 if (!isValidBST(root.left)) { return false; // 剪枝 } // 访问当前节点 if (pre != null && pre.val >= root.val) { return false; } pre = root; // 访问右子树 return isValidBST(root.right); /** * 中序遍历(非递归) */ /* if (root == null) return true; Stack<TreeNode> stack = new Stack<>(); TreeNode pre = null; while (!stack.isEmpty() || root != null) { while (root != null) { stack.push(root); root = root.left; } root = stack.pop(); if (pre != null && pre.val >= root.val) { return false; } pre = root; root = root.right; } return true; */ } }