主函数: 输入一个数组[9,3,20,1,8,15,27],从第0个节点开始构造二叉树
public class Main {
public static void main(String[] args) {
Main main=new Main();
Integer[] arr = new Integer[]{9,3,20,1,8,15,27};
/**
*将数组构造成二叉树,要传二个参数,arr代表数组,index表示截取哪一节点的子树
* 0节点的子树就是整棵树
* 1节点的子树是第二层的左子树
* 2节点的子树是第二层的右子树
* 3节点的子树是第三层的左子树
*/
TreeNode root = CreateBinaryTreeByArray.createBinaryTreeByArray(arr,0);
System.out.println("Hello World!----"+main.isValidBST(root));
}
}
createBinaryTreeByArray()函数如下:
(备注:采用先序遍历的顺序【根左右】依次给二叉树的每个节点赋值:)
public class CreateBinaryTreeByArray {
public static TreeNode createBinaryTreeByArray(Integer[] array, int index)
{
TreeNode tn = null;
if (index<array.length) {
Integer value = array[index];
if (value == null) {
return null;
}
tn = new TreeNode(value);
//先序遍历二叉树
//System.out.println("根:"+tn.value+" 左:"+tn.left+" 右:"+tn.right+"");
tn.left = createBinaryTreeByArray(array, 2*index+1);
//中序遍历二叉树
//System.out.println("根:"+tn.value+" 左:"+tn.left+" 右:"+tn.right+"");
tn.right = createBinaryTreeByArray(array, 2*index+2);
//后序遍历二叉树
//System.out.println("根:"+tn.value+" 左:"+tn.left+" 右:"+tn.right+"");
return tn;
}
return tn;
}
}
/**
* 节点
*/
public class TreeNode {
/**
* 节点值
*/
public int value;
/**
* 左节点
*/
public TreeNode left;
/**
* 右节点
*/
public TreeNode right;
public TreeNode(int value) {
this.value = value;
left = null;
right = null;
}
}
运行时过程图:
调试结果:
再附上一个算法(输入的数组是否符合二叉搜索树BST的结构):
public boolean isValidBST(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
sort(root, stack);
if (stack.empty()) return true;
TreeNode node = stack.pop();
while (node != null && !stack.empty()) {
TreeNode node1 = stack.pop();
if (node.value <= node1.value) return false;
node = node1;
}
return true;
}
public void sort(TreeNode treeNode, Stack<TreeNode> stack) {
if (treeNode == null) return;
if (treeNode.left != null) sort(treeNode.left, stack);
stack.push(treeNode);
if (treeNode.right != null) sort(treeNode.right, stack);
}
备注:
中序遍历二叉树,将数组的值从小到大压入栈中
if (node.value <= node1.value) return false;
因为是从小到大入栈,取的时候则从大到小取出来,后节点的值要小于前节点的值,该数组才满足BST。