How does inorder+preorder construct unique binary tree?

后端 未结 4 1704
刺人心
刺人心 2020-12-13 01:22

Recently, my questions were marked duplicate, like this , even if they weren\'t. So, let me start with following and then I\'ll explain my question.

Why this

4条回答
  •  时光说笑
    2020-12-13 01:51

    One question I would have asked the interviewer is regarding repeated elements. Two "different" binary trees can have the same preorder and inorder traversals if they have repetitive elements.

    As an example, consider the following case :

    inorder : {12, 12} preorder : {12, 12}

           12           12 
    
        /                  \
    
     12                     12
    

    Now coming to the case when there are unique elements. When we recursively approach a problem, we can always break bigger sets into tuples of 3. Let us say we have inorder traversal as {Left,Root,Right} and pre-order Traversal as {Root, Left , Right}.

    When we fixate the Root from the preorder traversal, the rest of the preorder traversal should be thought of as two sub-parts whose further details can be obtained from the inorder traversal. Observe that at each stage, we try to solve the standard three-node problem : we may not care much about how many "sub-problems" each node has because we know we would be getting to that point later.

提交回复
热议问题