Given a tree, you are supposed to tell if it is a complete binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤20) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a - will be put at the position. Any pair of children are separated by a space.
Output Specification:
For each case, print in one line YES and the index of the last node if the tree is a complete binary tree, or NO and the index of the root if not. There must be exactly one space separating the word and the number.
num_nodes = int(input()) nodes = [Node(i) for i in range(num_nodes)] for i in range(num_nodes): left, right = input().split() if left != "-": nodes[i].left = nodes[int(left)] nodes[i].left.father = nodes[i] if right != "-": nodes[i].right = nodes[int(right)] nodes[i].right.father = nodes[i]
root = nodes[0] while root.father isnotNone: root = root.father
defbfs(): global num_nodes, root, num_nodes, nodes max_level = int(pow(num_nodes, 0.5)) level = 0 que = Queue() que.put(root) whileTrue: if que.qsize() != pow(2, level): return"NO", root.index level += 1
if level != max_level: for i in range(que.qsize()): node = que.get() if node.left isnotNone: que.put(node.left) if node.right isnotNone: que.put(node.right)
else: nodes_last = num_nodes - pow(2, max_level) + 1 last_node = 0 for i in range(que.qsize()): node = que.get() if nodes_last != 0: if node.left: nodes_last -= 1 last_node = node.left.index else: return"NO", root.index if nodes_last != 0: if node.right: nodes_last -= 1 last_node = node.right.index else: return"NO", root.index if nodes_last == 0: return"YES", last_node