Continue learning
Practice related DSA questions in the same topic.
Visit a complete binary tree in root-left-right order and return its values. The input holds level-order values with no missing nodes.
Visit a complete binary tree in root-left-right order and return its values. The input holds level-order values with no missing nodes.
def solve(values, target): stack = [0] * (len(values)) out = [0] * (len(values)) if (len(values) == 0): return out top = 1 stack[0] = 0 count = 0 while (top > 0): top = (top - 1) node = stack[top] out[count] = values[node] count = (count + 1) right = ((node * 2) + 2) left = ((node * 2) + 1) if (right < len(values)): stack[top] = right top = (top + 1) if (left < len(values)): stack[top] = left top = (top + 1) return outVisit the root of the pending subtree.
Visit the root of the pending subtree.
When two rooms branch off, put the later room on the to-do pile before the room to visit now.
A stack drives traversal. Push the right child first so the left child is popped first.
O(n) time · O(n) allocated stack and output auxiliary space
Worked example · {"values":[8,4,9,1,6],"target":0} ⇒ [8,4,1,6,9]
Edge case 1 · {"values":[],"target":0} ⇒ []
Edge case 2 · {"values":[7],"target":0} ⇒ [7]
Pushing the left child first reverses the intended visit order.
How could a null marker represent sparse trees?