LeetCode刷题MEDIM篇Validate Binary Search Tree
题目
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:
Input:
2
/ \
1 3
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
is 5 but its right child's value is 4.
十分钟尝试
很显然,利用递归解决这个问题,看代码:
/**
* 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) {
if(root==null){
return true;
}
if((root.left!=null&&root.left.val>=root.val)||(root.right!=null&&root.right.val<=root.val)){
return false;
}
return isValidBST(root.left)&&isValidBST(root.right);
}
}
有问题,对于 10,5,15,null,null,6,20测试通过,因为不仅仅要比较当前根节点,要比较所有的根节点。
更改一下思路吧。试试二叉树的遍历方法。我们利用中序遍历,因为中序遍历后,输出就是有序的。所以寻找二叉树第k小第数字也是利用中序遍历做的,详细看这道题目:
https://leetcode.com/problems/kth-smallest-element-in-a-bst/
中序遍历输出是一个升序排列。我们记录一下前一个元素,然后比较是否小于前一个,如果大于就是bst,反之不是。
/**
* 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) {
if(root==null){
return true;
}
Deque<TreeNode> stack=new LinkedList();
List<Integer> res=new ArrayList();
TreeNode curr=root;
while(curr!=null||!stack.isEmpty()){
while(curr!=null){
stack.push(curr);
curr=curr.left;
}
curr=stack.pop();
if(res.size()>0&&curr.val<=res.get(res.size()-1)){
return false;
}
res.add(curr.val);
curr=curr.right;
}
return true;
}
}
测试通过,但是效率不是很高。因为是有序的,所以每次取出最后一个元素跟当前相比,如果增加继续,反之返回false
看了别人的思路,遍历的时候可以记录前一个节点,这样不用每次都是list中寻找,虽然时间复杂度是O(1),但是也是有差别的。修改后效率有所提高。
/**
* 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) {
if(root==null){
return true;
}
Deque<TreeNode> stack=new LinkedList();
List<Integer> res=new ArrayList();
TreeNode curr=root;
TreeNode pre=null;
while(curr!=null||!stack.isEmpty()){
while(curr!=null){
stack.push(curr);
curr=curr.left;
}
curr=stack.pop();
if(pre!=null&&pre.val>=curr.val){
return false;
}
res.add(curr.val);
pre=curr;
curr=curr.right;
}
return true;
}
}