其他分享
首页 > 其他分享> > 给定一个数组,返回对应的二叉树结构

给定一个数组,返回对应的二叉树结构

作者:互联网

例如:给定数组[1,2,2,3,4,4,3]
返回为:
在这里插入图片描述
代码如下:

public static TreeNode buildTree(Integer[] arr){
        if(arr.length==1) return new TreeNode(arr[0]);
        Queue<TreeNode> queue=new LinkedList<>();
        TreeNode root=new TreeNode(arr[0]);
        queue.offer(root);
        for(int left=1;left<arr.length;left+=2){
            TreeNode poll = queue.poll();
            if(arr[left]!=null){
                poll.left=new TreeNode(arr[left]);
                queue.offer(poll.left);
            }
            if(left+1<arr.length){
                if(arr[left+1]!=null){
                    poll.right=new TreeNode(arr[left+1]);
                    queue.offer(poll.right);
                }
            }
        }
        return root;
    }

model类

public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {
        }
        TreeNode(int val) {
            this.val = val;
        }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

标签:arr,right,TreeNode,val,给定,二叉树,数组,poll,left
来源: https://blog.csdn.net/weixin_43978420/article/details/123608124