Printing BFS (Binary Tree) in Level Order with Specific Formatting

前端 未结 15 1387
情歌与酒
情歌与酒 2020-12-04 13:00

To begin with, this question is not a dup of this one, but builds on it.

Taking the tree in that question as an example,

    1 
   / \\
  2   3
 /            


        
15条回答
  •  Happy的楠姐
    2020-12-04 13:19

    A version that doesn't require extra storage:

    std::deque bfs;
    bfs.push_back(start);
    int nodesInThisLayer = 1;
    int nodesInNextLayer = 0;
    while (!bfs.empty()) {
        Node front = bfs.front();
        bfs.pop_front();
        for (/*iterate over front's children*/) {
            ++nodesInNextLayer;
            nodes.push_back(child);
        }
        std::cout << node.value;
        if (0 == --nodesInThisLayer) {
            std::cout << std::endl;
            nodesInThisLayer = nodesInNextLayer; 
            nodesInNextLayer = 0;
        } else {
            std::cout << " ";
        }
    }
    

    P.S. sorry for the C++ code, I'm not very fluent in Python yet.

提交回复
热议问题