题意
Given a binary tree, determine if it is a valid binary search tree (BST).
判定一棵树是不是二分搜索树。
思路:判定中序遍历出来的结果是不是递增的。
public class Solution {
List<Integer> list=new ArrayList<Integer>();
public boolean isValidBST(TreeNode root) {
if(root==null) return true;
if(root.left==null && root.right==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){
inOrderTraversal(root.left);
list.add(root.val);
inOrderTraversal(root.right);
}
}
}
网上还有个解法,也是中序遍历,但是写法不一样,对于这种写法,我还不是太理解唉……
- public class Solution {
- // Keep the previous value in inorder traversal.
- TreeNode pre = null;
- public boolean isValidBST(TreeNode root) {
- // Traverse the tree in inorder.
- if (root != null) {
- // Inorder traversal: left first.
- if (!isValidBST(root.left)) return false;
- // Compare it with the previous value in inorder traversal.
- if (pre != null && root.val <= pre.val) return false;
- // Update the previous value.
- pre = root;
- // Inorder traversal: right last.
- return isValidBST(root.right);
- }
- return true;
- }
- }
根据这道题,又顺便搜索了B- B+ B* 又理解了一遍思想。大话数据结构上还讲解了2-3树,2-3-4树,由这俩是B树的特例引出了B树。大话上就是讲的挺易于理解的,讲故事一样的。
关于B树和B-树,网上的概念有争议。
大话数据结构上是 B树即B-tree,是一种平衡的多路查找树。
而另一说法是B树是指二叉搜索树,B-树是多路查找树。
先不过多纠结了,暂且把每棵树的具体思想搞清楚。