📅  最后修改于: 2023-12-03 15:28:36.333000             🧑  作者: Mango
This is a question from the computer science and engineering subject of GATE 2017 MOCK II. The question tests an individual's understanding of trees, traversal orders, and algorithmic complexity. The question is as follows:
Consider a binary tree with n nodes numbered 1 to n. It is possible to preorder-traverse to identify whether a node i has a left child or not. If it has a left child, we visit the left subtree; otherwise, we visit the right subtree.
Suppose we are given a sequence of n integers from 1 to n, with repetition allowed, which corresponds to the preorder traversal of a binary tree with n nodes. Suppose the root of the tree is numbered 1. A stack S is used to construct the tree incrementally. When the algorithm visits a node i for the first time, it pushes i onto the stack S. When the algorithm visits a node i for the second time, the top element on the stack is removed, provided it is i. Otherwise, the sequence is not a valid preorder traversal of a binary tree with n nodes. For example, the sequence 2, 1, 3, 2, … is not valid preorder traversal of any binary tree with n > 1 nodes.
Consider the following algorithm:
(x, S)
What is the time complexity of this algorithm when the input sequence corresponds to a valid preorder traversal of a binary tree with n nodes?
(A) O(n) (B) O(n log n) (C) O(n^2) (D) O(n^n)
The question asks us to find the time complexity of the algorithm when the input sequence corresponds to a valid preorder traversal of a binary tree with n nodes. Remember that the given algorithm builds a binary tree incrementally using a stack. We push a node onto the stack only for the first time we visit it; we don't consider the stack when we visit it the second time. If a node is not the top of the stack when visiting it the second time, we know that the sequence doesn't correspond to a valid preorder traversal. Therefore, we visit each node at most twice.
Since we visit each node at most twice, the worst-case time complexity of the algorithm is O(n).
Therefore, the correct answer is option (A) O(n).
def validate_preorder_traversal(preorder):
stack = []
i = 0
n = len(preorder)
x = preorder[0]
while True:
if stack and stack[-1] == x:
stack.pop()
i += 1
if i >= n:
return True
x = preorder[i]
else:
stack.append(x)
i += 1
if i >= n:
return False
x = preorder[i]