public void preorder(int index) {
// Create Content
if(aTree[index] != null) {
System.out.print(aTree[index]);
preorder(2 * index);
preorder(2 * index + 1);
}
}
Simple tree potential traversal function.
Array is a 32-size object array with an input index of 1.
Null value from aTree[12].
What I'm curious about is that after debugging, when the index becomes 16 and the if statement becomes false,
Preorder (2 * index + 1); it goes to this function.
What's the reason? Shouldn't the preorder function end automatically because the if statement is false?
Why
preorder(2 * index);
(index == 8) ->
preorder(16);
if(aTree[index] != null) == false ->
preorder(2 * index + 1); ->
preorder(17) ->
if(aTree[index] != null) == false ->
preorder(2 * index + 1); ->
preorder(4)
What's the reason for the function to go over? I don't understand it in my head
java recursive
In a given function, the preorder function is called twice in total, once in 2 * index and once in 2 * index+1. So this is how the program works, right?
preorder(1) ->preorder(2) ->preorder(4) ->preorder(8) ->preorder(16) ->null ->preorder(17)->null ->preorder(9) ->... ->... ->preorder(3)-> ...
So when if is false, the function ends and then you go to process the remaining functions that you still have to run. I don't know if it's explained because I'm not good at speaking.
© 2024 OneMinuteCode. All rights reserved.