题目:
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
题意:
判断这二叉树是不是二叉查找树
解题思路:
我们可以利用中序遍历的特点,中序遍历BST后整个结点集应该是一个有序集合
如果当前结点小于等于前一个结点那么可以直接返回false
代码:
ArrayList<Integer> list = new ArrayList<Integer>();
public boolean isValidBST(TreeNode root) {
if(root == null) {
return true;
}
inorderTraversal(root);
for(int i = 1;i< list.size() ;i++) {
if(list.get(i) <= list.get(i-1)) {
return false;
}
}
return true;
}
public void inorderTraversal(TreeNode root){
if(root == null) {
return;
}
inorderTraversal(root.left);
list.add(root.val);
inorderTraversal(root.right);
}