題目
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;
}
}