简体   繁体   English

C++ 为二叉树取多个输入

[英]C++ Taking multiple inputs for binary tree

I am struggling how to handle multiple inputs for the binary tree.我正在努力如何处理二叉树的多个输入。

The input format is:输入格式为:

  • The first line takes an integer n as an input representing level of tree.第一行将 integer n作为表示树级别的输入。
  • Next n + 1 lines contain the nodes in the tree in level order.接下来的n + 1行按级别顺序包含树中的节点。

Example input:示例输入:

2
1
2 3
4 5 6 7

Pictorial representation of above inputs:上述输入的图示:

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

I want to put those values from second line to last line into vector, but it is hard to get the inputs like above.我想将这些值从第二行到最后一行放入向量中,但很难获得像上面这样的输入。

Here is what I tried:这是我尝试过的:

int main(void) {
    vector<int> tree;
    int lv, num;
    int treeSize = 1;

    cin >> lv;

    for(int i = 0; i <= lv; i++) {
        while(tree.size() < treeSize && cin >> num) {
            tree.push_back(num);
        }
        treeSize += (i + 1) * 2;
    }

    return 0;
}

My code doesn't work properly.我的代码无法正常工作。 For instance, above example input has to have total 7 nodes, but if I put too many numbers in one line as input, it exceeds 7 nodes.例如,上面的示例输入必须总共有 7 个节点,但是如果我在一行中输入太多数字作为输入,它就会超过 7 个节点。

Is there any proper way to get inputs in case of this?在这种情况下,是否有任何适当的方法来获取输入?

The code looks correct at a glance.代码一目了然。 I would trace it in a debugger.我会在调试器中跟踪它。 IMHO your code is a bit difficult.恕我直言,您的代码有点困难。 I would do the array filling like below.我会像下面那样进行数组填充。

int main(void) {
    vector<int> tree;
    int lv, num;

    cin >> lv;

    for(int i = 0, lvSize = 1; i <= lv; i++; lvSize *= 2) {
        for (int j = 0; j < lvSize; && cin >> num; j++) {
            tree.push_back(num);
        }
    }

    return 0;
}

Since you read a tree in a vector, you know the number of elements and the code can be simplified and reduced a bit more.由于您在向量中读取树,因此您知道元素的数量,并且可以进一步简化和减少代码。

int main(void) {
    vector<int> tree;
    int lv, num;

    cin >> lv;
    int size = (1 << (lv + 1)) - 1;   // This is pow(2, lv + 1) - 1

    for(int i = 0; i < size; i++) {
        tree.push_back(num);
    }

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM