天天看点

算法:非递归遍历二叉树

public class Node {

private int node;

private Node leftNode;

private Node rightNode;

public Node(int node){

this.node = node;

}

public int getNode() {

return node;

}

public void setNode(int node) {

this.node = node;

}

public Node getLeftNode() {

return leftNode;

}

public void setLeftNode(Node leftNode) {

this.leftNode = leftNode;

}

public Node getRightNode() {

return rightNode;

}

public void setRightNode(Node rightNode) {

this.rightNode = rightNode;

}

}

import java.util.Stack;

public class Two {

public static void main(String[]args){

Node A = new Node(6);

Node B = new Node(3);

Node C = new Node(9);

Node D = new Node(1);

Node E = new Node(5);

Node F = new Node(7);

Node G = new Node(2);

Node H = new Node(4);

Node I = new Node(8);

A.setLeftNode(B);

A.setRightNode(C);

B.setLeftNode(D);

B.setRightNode(E);

C.setLeftNode(F);

D.setRightNode(G);

E.setLeftNode(H);

F.setRightNode(I);

Stack<Node> stack = new Stack<Node>();

stack.push(A);

Node a = stack.pop();

preSearch(A);

}

static void preSearch(Node node){

Stack<Node> stack = new Stack();

while(node!=null || stack.size()>0){

if(node!=null){

System.out.println(node.getNode());

stack.push(node);

node = node.getLeftNode();

}else{

node = stack.pop();

node = node.getRightNode();

}

}

}

}