首先定义节点结构
// 节点结构
public class Node {
public int count;
private int val;
private Node left;
private Node right;
public Node(int val){
this.val = val;
}
public Node() {
}
// 获取方法
public int getVal(){
return this.val;
}
public Node getLeft(){
return this.left;
}
public Node getRight(){
return this.right;
}
// 赋值方法
public void setVal(int val){
this.val = val;
}
public void setLeft(Node left){
this.left = left;
}
public void setRight(Node right){
this.right = right;
}
}
树和结构
import java.util.Vector;
/**
* @Author: weiye
* @Date: Create in 14:47 2020/7/19
* @description:
*/
public class binaryTree {
public Node createTree_floor(int[] nums,int index,Node root){
if (nums.length == 0) {
return null;
}
if(index >=nums.length)
return null;
if(nums[index]>0)
{
root = new Node();
root.setVal(nums[index]);
}
else
return null;
Node left = createTree_floor(nums,index*2+1,root.getLeft());
root.setLeft(left);
Node right = createTree_floor(nums,index*2+2,root.getRight());
root.setRight(right);
return root;
}
public Node createTree_pre(Vector<Integer> vec,Node root){
if(vec.isEmpty()){
return null;
}
int nums= vec.get(0);
vec.remove(0);
if (nums<0)
{
return null;
}
root = new Node(nums);
root.setLeft(createTree_pre(vec,root.getLeft()));
root.setRight(createTree_pre(vec,root.getRight()));
return root;
}
public void preOrder(Node root){
if(root ==null)
return;
System.out.println(root.getVal());
preOrder(root.getLeft());
preOrder(root.getRight());
}
public void inOrder(Node root)
{
if (root ==null)
return;
inOrder(root.getLeft());
System.out.println(root.getVal());
inOrder(root.getRight());
}
public static void main(String[] args) {
int[] nums = {1,2,3,-1,-2,4,-1,-2,5,-3,6};
Vector<Integer> vector = new Vector();
for (int i = 0; i < nums.length; i++){
vector.add(nums[i]);
}
binaryTree b = new binaryTree();
Node root = new Node();
System.out.println(vector);
System.out.println(vector.get(0));
root = b.createTree_pre(vector,root);
b.preOrder(root);
System.out.println("----------");
b.inOrder(root);
}
}