Home > Back-end >  About order in binary tree non-recursive traversal problem
About order in binary tree non-recursive traversal problem

Time:10-13

Today to review the order in the binary tree non-recursive traversal, found within the loop, I use the if and while looking for the lower nodes effect is the same as
Create a tree this

In my code, whether the code in blue word, or code of the scarlet letter, it is concluded that the result is the same, want to ask why this
Public void iterTraverseTree (TreeNode node) {
Stack Stack=new Stack (a);
TreeNode current=node;

While (current!=null | |! Stack. The isEmpty ()) {
/* if (current!=null) {
Stack. Push (current);
The current=current. Left;
} */

while (current!=null) {
Stack. Push (current);
The current=current. Left;
}

If (current==null) {
The current=stack. Pop ();
System. The out. Println (current. Val);
The current=current. Right;
}

}
}

CodePudding user response:

Complete code below
 import Java. Util. Stack; 

Public class DataStruct_NonRecursiveTraversal {
//the definition of tree node
Public class TreeNode {
Int val.
TreeNode left;
TreeNode right;
TreeNode (int x) {val=x; }
}

//create a binary tree
Public TreeNode createTree () {
TreeNode a=new TreeNode (1);
TreeNode b=new TreeNode (2);
TreeNode c=new TreeNode (3);
TreeNode d=new TreeNode (4);
TreeNode e=new TreeNode (5);
TreeNode f=new TreeNode (6);
TreeNode g=new TreeNode (7);
A. eft=b;
A.r d.light=c;
B.l eft=d;
B.r d.light=e;
C.l eft=f;
C.r d.light=g;
Return a;
}

//for non-recursive: all left children into stack, define a element, the top point to the stack when the traverse cur to null,
//can be cur point to the new top, down to traverse the top, right, until the traverse the binary tree,
Public void iterTraverseTree (TreeNode node) {
Stack Stack=new Stack (a);
TreeNode current=node;

While (current!=null | |! Stack. The isEmpty ()) {
/* if (current!=null) {
Stack. Push (current);
The current=current. Left;
} */
While (current!=null) {
Stack. Push (current);
The current=current. Left;
}
If (current==null) {
The current=stack. Pop ();
System. The out. Println (current. Val);
The current=current. Right;
}

}
}



Public static void main (String [] args) {
DataStruct_NonRecursiveTraversal d=new DataStruct_NonRecursiveTraversal ();
D.i terTraverseTree (, dc reateTree ());
}

}

CodePudding user response:

Each end of the if, the next cycle or the if, and while the effect
  • Related