欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数组转二叉树

程序员文章站 2022-05-19 22:09:29
...

数组转二叉树

思路:

  • 准备数组
  • 构建树节点集合
  • 循环树节点集合构建二叉树
public class BinaryTreeDemo {

	public static void main(String[] args) {
		//原始数组中可以输入null,转为的二叉树缺少左节点
		//Integer[] arr = {1,2,3,4,5,null,7};
		Integer[] arr = {1,2,3,4,5,6,7};
		// 数组转为二叉树
        TreeNode node = arrayToTree(arr);
        // 二叉树前序遍历一下
        node.preNode();
	}
	
	/**
     * 数组转为二叉树
     * @param arr   输入原始数组
     * @return  返回二叉树的跟节点
     */
	public static TreeNode arrayToTree(Integer[] arr){
        int len = arr.length;
        List<TreeNode> nodes = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == null) {
                nodes.add(null);
            } else {
                nodes.add(new TreeNode(arr[i]));
            }
        }

        for (int i = 0; i < len/2; i++) {
            TreeNode node = nodes.get(i);

            if (2*i+1 < len){
                TreeNode left = nodes.get(2*i+1);
                node.setLeft(left);
            }
            if (2*i+2 < len) {
                TreeNode right = nodes.get(2*i+2);
                node.setRight(right);
            }
        }
        return nodes.get(0);
    }
    
}

class TreeNode{
    private Integer val;
    private TreeNode left;
    private TreeNode right;

    public Integer getVal() {
        return val;
    }

    public void setVal(Integer val) {
        this.val = val;
    }

    public TreeNode getLeft() {
        return left;
    }

    public void setLeft(TreeNode left) {
        this.left = left;
    }

    public TreeNode getRight() {
        return right;
    }

    public void setRight(TreeNode right) {
        this.right = right;
    }

    public TreeNode () {}
    public TreeNode (Integer val) {
        this.val = val;
    }
    public TreeNode (Integer val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
        @Override
    public String toString() {
        return "TreeNode{" +
                "val=" + val +
                '}';
    }

//    前序遍历
    public void preNode(){
        System.out.println(this.val);
        if (this.left != null){
            this.left.preNode();
        }
        if (this.right != null){
            this.right.preNode();
        }
    }

//    中序遍历
    public void midNode(){
        if (this.left != null) {
            this.left.midNode();
        }
        System.out.println(this.val);
        if (this.right != null) {
            this.right.midNode();
        }
    }

//    后序遍历
    public void postNode(){
        if (this.left != null) {
            this.left.postNode();
        }
        if (this.right != null) {
            this.right.postNode();
        }
        System.out.println(this.val);
    }
 }