How does this inorder traversal algorithm work?

后端 未结 3 546
眼角桃花
眼角桃花 2020-12-18 07:38

I don\'t have much experience with recursion, so I\'m having a hard time determining exactly how this algorithm works:

 public static void inorder(Node

        
3条回答
  •  没有蜡笔的小新
    2020-12-18 08:06

    The best way to understand recurssion is try to state your problem verbally and then work through an example (You can refer @Mark Carpenter 's example) :

    The way inorder search works is as follows :

    Say I am at node n :

    1) First access all nodes to left of node n. (i.e n.getLeft()) in inorder fashion , the best way to achieve this is to call inorder() recursively and pass it the left child of n.

    2) Now when the function reaches this step, it had already printed all left children of Node n. So now print Node n.

    3) Now access all nodes to right of node x. (i.e n.getRight()) in inorder fashion, the best way to achieve this is to call inorder() recursively and pass it the right child of n.

提交回复
热议问题