# 03192020 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. 10 /\ 5 18 /\ /\ 2 7 15 20 ``` /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isValidBST(TreeNode root) { return helper(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } public boolean helper(TreeNode root, long min, long max) { if (root == null) return true; if (root.val >= max || root.val <= min) return false; return helper(root.left, min, root.val) && helper(root.right, root.val, max); } } ``` ``` min = max = 5 ``` ``` public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<>(); if(root == null) return list; Stack<TreeNode> stack = new Stack<>(); while(root != null || !stack.empty()){ while(root != null){ stack.push(root); root = root.left; } root = stack.pop(); list.add(root.val); root = root.right; } return list; } ``` ``` public boolean isValidBST(TreeNode root) { if (root == null) return true; Stack<TreeNode> stack = new Stack<>(); TreeNode pre = null; while (root != null || !stack.isEmpty()) { while (root != null) { stack.push(root); root = root.left; } root = stack.pop(); if(pre != null && root.val <= pre.val) return false; pre = root; root = root.right; } return true; } ``` 10 /\ 5 18 /\ /\ 2 7 15 20 stack : 10 -> 5 -> 2 root: 2 pre: null stack : 10 -> 5 root: null pre: 2 stack : 10 root: 7 pre: 5 ``` public boolean isValidBST(TreeNode root) { if (root == null) return true; Stack<TreeNode> stack = new Stack<>(); TreeNode pre = null; while (root != null || !stack.isEmpty()) { while (root != null) { stack.push(root); root = root.left; } root = stack.pop(); if(pre != null && root.val <= pre.val) return false; pre = root; root = root.right; } return true; } ```