题目
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.
方法一
中序遍历二叉树,如果前一个元素始终比后一个大,则返回true,否则返回false。public boolean isValidBST(TreeNode root) { if (root == null) { return true; } TreeNode node = root; Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode pre = null; while(node != null || !stack.isEmpty()) { while(node != null) { stack.push(node); node = node.left; } TreeNode cur = stack.pop(); if (pre == null) { pre = cur; } else { if (pre.val >= cur.val) { return false; } pre = cur; } node = cur.right; } return true; }
方法二
使用递归。private boolean check(TreeNode node, int min, int max){ if (node == null) { return true; } int val = node.val; if (val > min && val < max) { return check(node.left, min, val) && check(node.right, val, max); } else { return false; } } public boolean isValidBST(TreeNode root) { return check(root, Integer.MIN_VALUE, Integer.MAX_VALUE); }