Leetcode原题:给一个二叉树,判断这个二叉树是不是二叉搜索树。
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.
A single node tree is a BST
我的思路是用BFS遍历这棵树,然后比较left child,right child是不是符合条件。
但是运行的时候,符合条件的树可以通过,不符合条件的树会一直给我返回空指针异常。
比如这棵树:
{1,#,2,3}
返回:Runtime Error
Exception in thread "main" java.lang.NullPointerException at Solution.isValidBST(Solution.java:35) at Main.main(Main.java:20)
请问为什么会给我报错呢?我只是return false;而已啊?
谢谢。
下面是我的代码:
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if the binary tree is BST, or false
*/
public boolean isValidBST(TreeNode root) {
// write your code here
Queue<TreeNode> queue = new LinkedList<TreeNode>();
if(root == null){
return true;
}
queue.offer(root);
while(queue.peek() != null){
TreeNode parent = queue.poll();
if(parent.left == null && parent.right == null){
return true;
}
else if(parent.left != null && parent.right == null){
if(root.val >= root.left.val){
queue.offer(parent.left);
}
else{
return false;
}
}
else if(parent.left == null && parent.right != null){
if(root.val <= root.right.val){
queue.offer(parent.right);
}
else{
return false;
}
}
else{
if(root.val >= root.left.val && root.val <= root.right.val){
queue.offer(parent.left);
queue.offer(parent.right);
}
else{
return false;
}
}
}
return false;
}
}
能否给出构造 {1,#,2,3}这棵树的代码?