How to create a binary tree

前端 未结 5 1156
感情败类
感情败类 2020-12-14 05:17

I did\'nt mean binary search tree.

for example, if I insert values 1,2,3,4,5 in to a binary search tree the inorder traversal will give 1,2,3,4,5 as output.

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 05:35

    If I understand you correctly, you want to create a binary tree from an array

    int[] values = new int[] {1, 2, 3, 4, 5};
    BinaryTree tree = new BinaryTree(values);
    

    this should prepopulate the binary tree with the values 1 - 5 as follows:

        1
       / \
      2   3
     / \
    4   5
    

    this can be done using the following class:

    class BinaryTree
    {
        int value;
        BinaryTree left;
        BinaryTree right;
    
        public BinaryTree(int[] values) : this(values, 0) {}
    
        BinaryTree(int[] values, int index)
        {
            Load(this, values, index);
        }
    
        void Load(BinaryTree tree, int[] values, int index)
        {
            this.value = values[index];
            if (index * 2 + 1 < values.Length)
            {
                this.left = new BinaryTree(values, index * 2 + 1);
            }
            if (index * 2 + 2 < values.Length)
            {
                this.right = new BinaryTree(values, index * 2 + 2);
            }
        }
    }
    

提交回复
热议问题