二叉树中序遍历打印节点信息

public static void main(String[] args){
BinaryTree tree = create();
MidOrderPrint(tree);
}


static class BinaryTree{
String data;
BinaryTree left;
BinaryTree right;

public BinaryTree(String data) {
this.data = data;
}
}

/**
* ........... a
* ........../.....\
* ........b........c
* ....../....\
* ....d........e
* .....\ ...../
* ......f....g

* dfbgeac
*/
private static BinaryTree create(){
BinaryTree a = new BinaryTree("a");

BinaryTree b = new BinaryTree("b");
BinaryTree c = new BinaryTree("c");
a.left = b;
a.right = c;

BinaryTree d = new BinaryTree("d");
BinaryTree e = new BinaryTree("e");

b.left = d;
b.right = e;

BinaryTree f = new BinaryTree("f");
BinaryTree g = new BinaryTree("g");

d.right = f;

e.left = g;

return a;
}

static void MidOrderPrint(BinaryTree tree){
if(tree == null) return ;

Stack<BinaryTree> stack = new Stack<>();
BinaryTree cur = tree;

while(!stack.isEmpty() || cur != null){
if(cur != null){
stack.push(cur);
cur = cur.left;
}else{
cur = stack.pop();
System.out.print(cur.data);
cur = cur.right;
}
}
}
打赏