构造二叉树的逻辑是什么?

时间:2017-08-15 05:30:30

标签: c++ data-structures tree

我有一个while循环,它连续取整数直到输入-1。必须将这些元素插入二叉树(而不是BST)。如果它是BST,我们有条件插入新节点。但是我如何构建二叉树呢?

我的意思是如果节点是1,2,3,4,5,6 ......那么 1是根,2和3是节点1的左右子节点, 4和5是节点2的左右子节点,6节点3是节点3的子节点,如下所示:

{{1}}

如何创建这样的树?

2 个答案:

答案 0 :(得分:2)

执行此操作的一种简单方法是使用 级别订单遍历 。 每当您发现其左或右子节点为NULL的节点时,请将新节点作为该节点的子节点附加;如果左边和右边都是NULL,则附加为左子节点,否则附加为右子节点。

headers

答案 1 :(得分:0)

WhozCraigcomment概述的算法可以通过以下代码实现:

/* Create a binary tree with nodes presented in BFS order */
#include <cassert>
#include <iostream>
#include <vector>
#include <iomanip>

using std::vector;
using std::cout;
using std::cin;
using std::ostream;
using std::setw;

struct node
{
    int data;
    node *left;
    node *right;
    node(int n) : data(n), left(0), right(0) { }
};

void print_bt(const node *root);

int main()
{
    vector<node> v;
    int n;

    // Read data to EOF or a negative value
    while (cin >> n && n >= 0)
        v.push_back(node(n));

    // Create binary tree
    for (size_t i = 0; i < v.size()/2; i++)
    {
        assert(2*i+1 < v.size());
        v[i].left = &v[2*i+1];
        if (2*i+2 < v.size())
            v[i].right = &v[2*i+2];
    }

    // Print binary tree
    print_bt(&v[0]);

    return 0;
}

// print_bt() presents the data so that if you mentally rotate the
// output through 90º clockwise (so the root is at the top), then the
// left child appears on the left and the right on the right.  Reversing
// the order of left/right leaves that as somewhat confusing.
void print_bt(const node *root)
{
    static int level = 0;
    if (root != nullptr)
    {
        level++;
        print_bt(root->right);
        cout << setw(4*level) << root->data << '\n';
        print_bt(root->left);
        level--;
    }
}

例如,给定数字1到6作为输入,它产生:

       3
           6
   1
           5
       2
           4

并将数字1到15作为输入,它产生:

              15
           7
              14
       3
              13
           6
              12
   1
              11
           5
              10
       2
               9
           4
               8

如果您可视化树木顺时针旋转90º,那么1位于顶部会有所帮助。