first there should be a queue or stack to store the next layer elements, as the tree go deeper, there are many branches, which requires a contianer to track what’s the elements in next layer. stack always pop out the top element(FILO), which actually set the input elements in a reversed order as tree elements; queue can pop out the first element(FIFO), which can set the input elements in the same order in tree elements. so here pick std::queue.
the input array can used std::vector, each time pop_front(), which basically read the array in order. and each pop_front element constructs a new TreeNode
. if the layer container is empty(), then it’s the root layer; else it’s a branch layer. growing the tree in each branch layer, need update the next layer container.
for each new inserting element, either insert to left or right of node A in parent layer or insert to the A’s sibling node B. then pop out the node which already has both kids.
when traversling to the last node in parent layer, and if both the kids are filled-in, then there is a turning point, need to swap next_parent layer as parent layer.
|
|
how to deal with NULL
during struct constructure? if both (int x)
and (TreeNode* p)
constructor are defined, which will lead to ambisious when new TreeNode(NULL).
|
|