1.题目描述
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.
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
- 节点的左子树只包含小于当前节点的数。
- 节点的右子树只包含大于当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。
Example 1:
1 | 2 |
Example 2:
1 | 5 |
2.Solutions
I will show you all how to tackle various tree questions using iterative inorder traversal. First one is the standard iterative inorder traversal using stack. Hope everyone agrees with this solution.
Question : 94. Binary Tree Inorder Traversal
1 | public List<Integer> inorderTraversal(TreeNode root) { |
Now, we can use this structure to find the Kth smallest element in BST.
Question : 230. Kth Smallest Element in a BST
1 | public int kthSmallest(TreeNode root, int k) { |
We can also use this structure to solve BST validation question.
Question : 98. Validate Binary Search Tree
1 | public boolean isValidBST(TreeNode root) { |
方案二
Basically what I am doing is recursively iterating over the tree while defining interval <minVal, maxVal>
for each node which value must fit in.
1 | public boolean isValidBST(TreeNode root) { |