Home > Back-end >  Binary tree traversal, non-recursive sequence traversal of the problem
Binary tree traversal, non-recursive sequence traversal of the problem

Time:09-27





Running result: printing, indeed, but an error




The code is as follows:
Node types:
Public class BinTrNode {

Public int data;
BinTrNode Left;
BinTrNode right;

BinTrNode BinTrNode public BinTrNode (int data, left, right) {//pay attention to is the constructor to create nodes!!!!!!
This data=https://bbs.csdn.net/topics/data;
This. Left=Left;
This. Right=right;
}

}

Main function:
Import the Java. Util. Stack;

The import sun. Print. Resources. The serviceui;

/* * 1
* 2, 3,
* 4 5 n 10
* 7 8 9 n n 11
*/

Public class BinTrtest {

The static BinTrNode J=new BinTrNode (11, null, null);
The static BinTrNode I=new BinTrNode (10, null, J);
The static BinTrNode H=new BinTrNode (9, null, null);
The static BinTrNode G=new BinTrNode (8, null, null);
The static BinTrNode F=new BinTrNode (7, null, null);
The static BinTrNode E=new BinTrNode (5, H, null);
The static BinTrNode D=new BinTrNode (4, F, G);
The static BinTrNode C=new BinTrNode (3, null, I);
The static BinTrNode B=new BinTrNode (2, D, E);
The static BinTrNode A=new BinTrNode (A, B, C);

/* *
* non-recursive implementation sequence traversal ideas: 1, to get a node, a push operation, and to traverse the left subtree
* 2, the left end of the tree traversal, pop element of the stack, and print the
* 3, traverse its right subtree
*/
//in the sequence traversal
Public static void Inroottravelsal BinTrNode (b) {
Stack Stack=new Stack (a);
BinTrNode node=b;
While (node!=null | | stack!=null) {
While (node!=null) {
Stack. Push (node);
The node=node. Left;
}
If (stack!=null) {
The node=stack. Pop ();
System. The out. Print (node. Data);
The node=node. Right;
}

}
}

Public static void main (String [] args) {
//in the non-recursive sequence
System. The out. Println (" ");
Inroottravelsal (A);

}

}

  • Related