如何使用节点将Int / String数组转换为二叉树?

时间:2019-12-07 02:29:56

标签: java algorithm data-structures

在Java中,使用提供的节点类编写一个名为tree builder的方法

tree builder是一种采用int数组输入并按顺序构建树的方法 助教说明:道歉还应该有一个帖子,以便对此进行遍历 树

从这些数组构建

预订[19 47 23 -2 55 63 94 28]

顺序[23 47 55 -2 19 63 94 28]
发布订单[23 55 -2 47 28 94 63 19] 这棵树

            | 19 |
            +----+
           /      \
          /        \
      +----+      +----+
      | 47 |      | 63 |
      +----+      +----+
     /      \           \
    /        \           \
+----+      +----+      +----+
| 23 |      | -2 |      | 94 |
+----+      +----+      +----+
           /                  \
          /                    \
      +----+                  +----+
      | 55 |                  | 28 
public class TreeNode {
    public int data;       // data stored at this node
    public TreeNode left;  // reference to left subtree
    public TreeNode right; // reference to right subtree

    // post: constructs a leaf node with given data
    public TreeNode(int data) {
        this(data, null, null);
    }

    // post: constructs a node with the given data and links
    public TreeNode(int data, TreeNode left, TreeNode right) {
        this.data = data;
        this.left = left;
        this.right = right;
    }
}

public class Tree {
    private TreeNode root;

    public void treeBuilder(int[] array,int[] array) {
    for(int i = 0; i<array.length; i++) {
     // this is where I initalize a node but I'm not sure
     // how to build in pre-order
   }

   }
}

我知道如何以基本遍历的顺序遍历来打印树 但我不确定如何从具有int数组转变为具有树节点

2 个答案:

答案 0 :(得分:0)

如何从TreeNode 或两个

中获取int[]

根节点的值恰好出现在预订顺序的开头,随后是子树中的所有值,每个值都是连续的。

1)从预定顺序中取一个值
按顺序找到它:
左侧子树中的所有值都将出现在前面,所以您知道它们的计数
右侧子树中的所有值都将出现在
之后 递归构造2)左侧和3)右侧子树
使用1),2)和3)实例化TreeNode

答案 1 :(得分:0)

因为我对问题的理解不正确,所以编辑了我的答案。

他希望根据这三个遍历结果来构建树。

解决方案在这里给出:https://www.geeksforgeeks.org/construct-a-binary-tree-from-postorder-and-inorder/