#P17013. [GESP202606 六级] 满二叉树

[GESP202606 六级] 满二叉树

Problem Description

Given a rooted binary tree with nn nodes, the nodes are numbered in order as 1,2,…,n1, 2, \dots, n, and the root node is numbered 11.

For node ii, let the index of its left child be lil_i, and the index of its right child be rir_i. In particular, if the left child does not exist then li=0l_i = 0, and if the right child does not exist then ri=0r_i = 0.

Each node in the tree corresponds to a subtree rooted at that node. You need to find, among all nn subtrees of the given rooted tree, how many of them are full binary trees.

A full binary tree means a binary tree where all leaves have the same depth, and every non-leaf node has exactly two children. For example, the following three binary trees are all full binary trees:

()   ()        ()
    /  \      /  \
   ()  ()   ()    ()
           /  \  /  \
          ()  ()()  ()

In the above binary tree with 33 nodes, there are 33 subtrees that are full binary trees (including the whole tree itself and all single leaf nodes).

Another example:

   (1)
   / \
 (2) (3)
     / \
   (4) (5)

In the above binary tree with 55 nodes, there are 44 subtrees that are full binary trees (including the subtree rooted at node 33, and all single leaf nodes).

Input Format

The first line contains a positive integer nn, representing the number of nodes in the rooted binary tree.

The next nn lines each contain two non-negative integers li,ril_i, r_i, representing the indices of the left child and right child of node ii. The integers are separated by spaces.

Output Format

Output one line containing one integer, representing the number of full binary trees among all subtrees.

4
2 3
4 0
0 0
0 0

2
3
2 3
0 0
0 0
3

Hint

Constraints

For 40%40\% of the test points, it is guaranteed that 1≤n≤5001 \le n \le 500.

For all test points, it is guaranteed that 1≤n≤1051 \le n \le 10^5.

Translated by ChatGPT 5