0

I am creating a binary tree out of string using BFS algorithm and I have a question: Why should I write "TreeNode node = tree.front();" after while loop instead of "root = tree.front();". Why I can't just use already created TreeNode root ?

TreeNode* helper(queue<string> &q) {
    string data = q.front(); q.pop();
    if (data == "#") return NULL;
    
    queue<TreeNode*> tree;
    TreeNode* root = new TreeNode(stoi(data));
    tree.push(root);

    while(!tree.empty()) {
        int size = tree.size();
        for (int i = 0; i < size; i++) {
            TreeNode* node = tree.front();

            string newNode = q.front(); q.pop();
            if (newNode != "#") {
                node -> left = new TreeNode(stoi(newNode));
                tree.push(node -> left);
            } 

            string newNode = q.front(); q.pop();
            if (newNode != "#") {
                node -> right = new TreeNode(stoi(newNode));
                tree.push(node -> right);
            }

            tree.pop();
        }
    }
    return root;
}

1 Answers1

1

Because root points to the root of the tree, which is what the function should return, and the root of the tree has already been determined (it is the first element of the input queue).

Writing root = tree.front() would make the last created node the root of the tree, and the tree would have only one element.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • Thanks! I had incorrect assumption, that while I am creating new TreeNode in left and right subtrees, they will be used as new Node – Sultan Saliev Aug 07 '20 at 07:54