How does this workaround algorithm work?

I don’t have much experience in recursion, so it’s hard for me to determine how this algorithm works:

 public static void inorder(Node<?> n)
 {
  if (n != null)
  {
   inorder(n.getLeft());
   System.out.print(n.data + " ");
   inorder(n.getRight());
  }
 }

I know that it visits the left and right child nodes of each node in the tree, but I just can’t understand why it works.

+4
source share
3 answers

I will try to take a picture.

Imagine a tree

           a
      b          c
   d    e     f     g

Each letter represents a Node object.

What happens when you go into the 'a' Node is that it will look at the first left Node and find the "b". Then it will call the same method on 'b' and wait until it returns

'b' Node 'd'. 'd' ,

'd' Node . Node , . "d". , "d", Node 'd', . "b" Node.

'b', Node of 'b'.

Node 'e' Node of e, null return. 'e'. Node of 'e', ​​ 'e'. "b" node.

'b' 'a', 'a' 'a'.

:

d b e a f c g

+12

, , . , , .

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

  • F inorder Node.
  • inorder B, inorder A.
  • A , , B...

( . .)

wiki tree

+2

- , ( @Mark Carpenter):

:

, node n:

1) node n. (i.e n.getLeft()) inorder, - inorder() n.

2) Now that the function reaches this step, it has already printed all the left children of node n. So type node n.

3) Now go to all nodes to the right of node x. (ie n.getRight ()) in a module inorder, the best way to achieve this is to call inorder () recursively and pass the right child element n to it.

+1
source

Source: https://habr.com/ru/post/1541160/


All Articles