0

I found the implementation for creating a binary tree with in-order and pre-order traversals (http://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/), and I understood everything except the following:

    // What does inStrt being greater than inEnd mean? 
    if (inStrt > inEnd) 
        return null;

    // Why does inStrt == inEnd mean having no children?
    if (inStrt == inEnd)
        return tNode;

    // Why is it that the first call has inIndex - 1 for inEnd, while for the second, inIndex + 1 for inStart? 
    tNode.left = buildTree(in, pre, inStrt, inIndex - 1);
    tNode.right = buildTree(in, pre, inIndex + 1, inEnd);

Thank you and will be sure to accept the answer

maja
  • 17,250
  • 17
  • 82
  • 125
  • Take a look how Quicksort, mergesort or any divide and conquar algorithm works, that will be helpful. – Kaidul Nov 12 '16 at 08:43
  • It doesn't mean having no children. It means this is the place where the insertion should occur. **But** if the tree doesn support duplicates, it is the same thing. – user207421 Nov 12 '16 at 08:58
  • (You could have left the original comments (even the code) intact and preceded that code block with in introductory _my questions appear as inline comments (`// how?`)_.) `inStrt` is greater than `inEnd` if the node from the pre-order data was found at the beginning of the range of in-order data before the call to construct left subtree, or at the range's end for right subtree: empty left/right subtree. Leaf nodes (no descendants/non-empy subtree) are handled by `inStrt == inEnd`. – greybeard Nov 12 '16 at 15:10
  • @KaidulIslam I did but still not understanding the reason for it... If you can explain it to me for learning purpose, would be helpful. And if you can write as an answer, I will accept it. –  Nov 12 '16 at 22:41
  • @EJP What is the reason for `inIndex-1` and `inIndex+1`? –  Nov 12 '16 at 22:42

0 Answers0