【问题标题】:Construct a binary tree from a sequence of values从一系列值构造二叉树
【发布时间】:2020-07-02 22:03:55
【问题描述】:

如何从一系列值构造二叉树。

Input: [4,9,0,5,1]
    4
   / \
  9   0
 / \
5   1

Input with null: [1,2,3,null,5,6,7]

       1
     /   \
    2     3
  /  \   /  \
null  5  6   7


注意:这棵树不是二叉搜索树。 节点按预先顺序插入(根、左、右)。 首先从左到右填充子节点。填满关卡后,进入下一个关卡。 我的直觉是保持对父节点的引用。

public class TreeNode {
    public int value;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(int x) {
        value = x;
    }
}

public static TreeNode createTree(List<Integer> values) {
   // ???
   // return the root node
}

我觉得问这个很愚蠢。

PS:我想知道这棵树是如何从输入 https://leetcode.com/problems/sum-root-to-leaf-numbers/ 构建的

PS2:Berto99 给出了递归方式的草案。想知道迭代方式(需要保留父节点的引用)

【问题讨论】:

  • 如何将null 值存储到int value

标签: java insert binary-tree


【解决方案1】:

从一堆堆中汲取灵感:

public static TreeNode createTree(List<Integer> values, int index) {
   TreeNode tree = new TreeNode(values[index]);
   if(index * 2 < list.size())
       tree.left = createTree(values, index * 2);
   if(index * 2 + 1 < list.size())
       tree.right = createTree(values, index * 2 + 1);
   return tree;
}

请记住,这适用于从 1 开始的索引,如果你想要从 1 开始的版本,你应该使用

public static TreeNode createTree(List<Integer> values, int index) {
   TreeNode tree = new TreeNode(values[index-1]); //   <<--- changed here
   if(index * 2 < list.size())
       tree.left = createTree(values, index * 2);
   if(index * 2 + 1 < list.size())
       tree.right = createTree(values, index * 2 + 1);
   return tree;
}

逻辑很简单,给定一个数组,root 是第一个元素,左子元素是 pos*2,右子元素是 pos*2 + 1(同样,第一个 = 1,而不是 0)

【讨论】:

  • 希望代码能正常工作,我好久没写 Java 代码了啊
  • 我明白了,索引是通过递归迭代的(不在循环中)。然后,初始化TreeNode root = createTree(values,1);
  • @RaymondChenon 完全正确
【解决方案2】:

@Berto99 给出了主要思路

使用输入 [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14] 可视化树

             0
        /          \
      1             2
    /   \         /    \
  3       4      5       6 
 / \    /  \    /  \    /  \
7   8  9   10  11  12  13  14

Substitute the value 3 by index then you can infer the recurrence for left and right node.
node(3).left = 7 = 2 * index + 1
node(3).right = 8 = 2 * index + 2

完整的微调代码是

    public static TreeNode createTree(List<Integer> values) {
        if (values == null || values.size() == 0) return null;
        TreeNode root = createTree(values, 0);
        return root;
    }

    private static TreeNode createTree(List<Integer> values, int index) {
        if (index >= values.size()) return null;

        Integer value = values.get(index);
        if (value == null) return null;

        TreeNode tree = new TreeNode(value);

        // tree(index).left = 2 * index + 1
        tree.left = createTree(values, index * 2 + 1);

        // tree(index).right = 2 * index + 2
        tree.right = createTree(values, index * 2 + 2);

        return tree;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    相关资源
    最近更新 更多