Question
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.
Solution 1 -- Recursive
According to the question, we can write recursive statements. Note here whole left/right subtree should be smaller/greater than the root.
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public boolean isValidBST(TreeNode root) { 12 if (root == null) 13 return true; 14 if (root.left != null && !smallerThanRoot(root, root.left)) 15 return false; 16 if (root.right != null && !greaterThanRoot(root, root.right)) 17 return false; 18 if (isValidBST(root.left) && isValidBST(root.right)) 19 return true; 20 return false; 21 } 22 23 private boolean greaterThanRoot(TreeNode root, TreeNode child) { 24 if (child.val <= root.val) 25 return false; 26 if (child.left != null) { 27 if (!greaterThanRoot(root, child.left)) 28 return false; 29 } 30 if (child.right != null) { 31 if (!greaterThanRoot(root, child.right)) 32 return false; 33 } 34 return true; 35 } 36 37 private boolean smallerThanRoot(TreeNode root, TreeNode child) { 38 if (child.val >= root.val) 39 return false; 40 if (child.left != null) { 41 if (!smallerThanRoot(root, child.left)) 42 return false; 43 } 44 if (child.right != null) { 45 if (!smallerThanRoot(root, child.right)) 46 return false; 47 } 48 return true; 49 } 50 }
Solution 2 -- Inorder Traversal
Inorder traversal of BST is an ascending array. Java Stack
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public boolean isValidBST(TreeNode root) { 12 // This problem can be looked as inorder traversal problem 13 // Inorder traversal of BST is an ascending array 14 List<Integer> inOrderResult = new ArrayList<Integer>(); 15 Stack<TreeNode> stack = new Stack<TreeNode>(); 16 TreeNode tmp = root; 17 while (tmp != null || !stack.empty()) { 18 if (tmp != null) { 19 stack.push(tmp); 20 tmp = tmp.left; 21 } else { 22 TreeNode current = stack.pop(); 23 inOrderResult.add(current.val); 24 tmp = current.right; 25 } 26 } 27 // Traverse list 28 if (inOrderResult.size() < 1) 29 return true; 30 int max = inOrderResult.get(0); 31 for (int i = 1; i < inOrderResult.size(); i++) { 32 if (inOrderResult.get(i) > max) 33 max = inOrderResult.get(i); 34 else 35 return false; 36 } 37 return true; 38 } 39 }
时间: 2024-10-14 04:37:49