edited by
10,852 views
33 votes
33 votes

Consider the following nested representation of binary trees: $(X \ Y \ Z)$ indicates $Y$ and $Z$ are the left and right subtrees, respectively, of node $X$. Note that $Y$ and $Z$ may be $NULL$, or further nested. Which of the following represents a valid binary tree?

  1. $(1 \ 2 \ (4 \ 5 \ 6 \ 7))$
  2. $(1 \ (2 \ 3 \ 4) \ 5 \ 6) \ 7)$
  3. $(1 \ (2 \ 3  \ 4) \ (5 \ 6  \ 7))$
  4. $(1 \ (2 \ 3 \ NULL) \ (4 \ 5))$
edited by

8 Answers

Best answer
41 votes
41 votes
  1. $\rightarrow  (4 \ 5 \ 6 \ 7)$ this part of answer is not correct. We have $(X \ Y \ Z)$ not $ (W \ X \ Y \ Z)$. So, this is wrong
  2. $\rightarrow 3$ closing paranthesis, $2$ opening paranthesis. This is wrong. 
  3. $\text{CORRECT}$ 
  4. $\rightarrow$ Here in $(1 \ (2 \ 3 \ NULL) \ (4 \ 5)) , (4 \ 5)$ this is not allowed. So this is wrong. (It should be $(4,5,NULL)$)
edited by
11 votes
11 votes

Option C is Ans  as it generates a valid binary tree as shown below fig.

No other option is eligible for given constraints of question.

               

7 votes
7 votes

To solve this question we have to look at two things: 1) In a binary tree, a node may have at most 2 children. 2) To construct binary tree from the given sequences above, innermost parenthesis should be worked first.

In Option A : ( 4 5 6 7 ) is there, which says that node 4 has got three children, which is wrong for a binary tree, and also in the question, only ( X Y Z ) is defined, i.e. a node X can have at most 2 children, which will be the roots of subtrees Y and Z.

In Option B : after working on innermost (2 3 4), where 2 is a node of the binary tree, 3 is left subtree of node 2 and 4 is right subtree of node 2. From this we get (1 2 5 6). Here 2 has come from the root of subtree ( 2 3 4 ). Now again we don't have any definition for ( 1 2 5 6). Hence invalid.

In Option C: after working on ( 2 3 4) and ( 5 6 7 ) we get ( 1 2 5 ) where 2 has come from the root of subtree ( 2 3 4 ) and 5 has come from the root of subtree ( 5 6 7 ). Now, in ( 1 2 5 ) node 1 is the root of the binary tree, and subtree with root 2 is the left subtree and subtree with root 5 is the right subtree at root node 1. Hence it is giving valid binary tree.

In Option D: It is given as ( 2 3 NULL), here N,U,L and L are given as different elements, which is again wrong as according to ( X Y Z) definition, a node can have at most 2 children.

Source :geeksforgeeks

Answer:

Related questions

48 votes
48 votes
4 answers
1
Kathleen asked Sep 14, 2014
17,471 views
Let LASTPOST, LASTIN and LASTPRE denote the last vertex visited in a postorder, inorder and preorder traversal respectively, of a complete binary tree. Which of the foll...
55 votes
55 votes
8 answers
2
Kathleen asked Sep 14, 2014
9,737 views
An $n \times n$ array $v$ is defined as follows:$v\left[i,j\right] = i - j$ for all $i, j, i \leq n, 1 \leq j \leq n$The sum of the elements of the array $v$ is$0$$n-1$$n...