题目链接:https://leetcode.com/problems/validate-binary-search-tree/?tab=Description
思路:二叉搜索树的中序遍历应该是递增的序列,可以通过判断中序遍历的序列是否是严格增长的,来判断二叉树是否是二叉搜索树。
Java代码如下:
public class Solution {
private List<TreeNode> nodeList = new LinkedList<TreeNode>();
// 中序遍历
public void midPrint(TreeNode root){
if(root == null){
return;
}
midPrint(root.left);
TreeNode node = root;
nodeList.add(node);
midPrint(root.right);
}
public boolean isValidBST(TreeNode root) {
midPrint(root);
if(nodeList == null || nodeList.size()==0){
return true;
} else {
int num = nodeList.get(0).val;
// 中序遍历是否是递增的,且数据不能重复
for(int i=1; i<nodeList.size(); i++){
if(nodeList.get(i).val <= num){
return false;
} else{
num = nodeList.get(i).val;
}
}
}
return true;
}
}