Inorder tree traversal: Which definition is correct?

前端 未结 14 1237
轮回少年
轮回少年 2020-12-24 03:42

I have the following text from an academic course I took a while ago about inorder traversal (they also call it pancaking) of a binary tree (not BST):

相关标签:
14条回答
  • 2020-12-24 04:16

    But according to (my understanding of) definition #1, this should be

    A, B, D, C, E, F, G, I, H
    

    Unfortunately, your understanding is wrong.

    Whenever you arrive at a node, you must descend to an available left node, before you look at the current node, then you look at an available right node. When you chose D before C, you didn't descend to the left node first.

    0 讨论(0)
  • 2020-12-24 04:17

    The proper traversal would be: as far left as possible with leaf nodes (not root nodes)

    Left Root Right

    A B NULL

    C D E

    Null F G

    H I NULL

    F is root or left, i am not sure

    0 讨论(0)
  • 2020-12-24 04:18

    In my bad attempt at the drawing here's the order that shows how they should be picked. alt text

    pretty much pick the node that is directly above the line being drawn,.

    0 讨论(0)
  • 2020-12-24 04:20

    If you read carefully you see that the first "definition" says to start left of the root and that the order of the nodes is determined by when you pass under them. So B is not the first node, as you pass it from the left on the way to A, then first pass under A after which you go up and pass under B. Therefore it seems that both definitions give the same result.

    0 讨论(0)
  • 2020-12-24 04:20

    For an inline tree traversal you have to keep in mind that the order of traversal is left-node-right. For the above diagram that you are conflicted on, your error occurs when you read a parent node before reading any leaf(children) nodes to the left.

    The proper traversal would be: as far left as possible with leaf nodes(A), return to parent node(B), move to the right, but since D has a child to its left you move down again(C), back up to C's parent(D), to D's right child(E), reverse back to the root(F), move to the right leaf(G), move to G's leaf but since it has a left leaf node move there(H), return to parent(I).

    the above traversal reads the node when I have it listed in parenthesis.

    0 讨论(0)
  • 2020-12-24 04:21

    I think the first binary tree with the root of a is a Binary tree which is not correctly constructed.

    Try to implement so that all the left side of the tree is less than the root and all the right side of the tree is greater than or equal to the root.

    0 讨论(0)
提交回复
热议问题