[算法-java] 数组转二叉树_(层次遍历)

11 篇文章 0 订阅
import java.util.LinkedList;

import static java.lang.System.out;

/**
 * 数组转二叉树
 * 测试用例:
 *{8,8,7,9,2,#,#,#,#,4,7},{8,9,2}
 * Integer.MIN_VALUE代表空节点#
 * Created by ZeHua on 2017/5/13.
 */
public class Array2BinTree {
    /**
     * 用树的层次遍历的方法转二叉树
     * @param array
     * @return
     */
    public static TreeNode array2BinTree(int[] array){
        if(array.length==0){
            return null;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        int index = 0;
        TreeNode root = new TreeNode(array[index++]);
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();

            if(index<array.length){
                cur.left=new TreeNode(array[index++]);
                if(cur.left.val!=Integer.MIN_VALUE){
                    queue.add(cur.left);
                }else {//空结点不入队
                    cur.left=null;
                }

            }
            if(index<array.length){
                cur.right=new TreeNode(array[index++]);
                if(cur.right.val!=Integer.MIN_VALUE){
                    queue.add(cur.right);
                }else {//空结点不入队
                    cur.right=null;
                }

            }
        }

        return root;
    }

    public static void main(String[] args) {
        int[] a1 = {8,8,7,9,2,Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE,4,7};
        int[] a2 = {8,9,2};
        TreeNode t1 = array2BinTree(a1);
        TreeNode t2 = array2BinTree(a2);
        out.println();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值