1、节点类
public class Node {
private int data;
private Node left;
private Node right;
public Node(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
}
2、算法实现类(递归实现)
public class FindTree {
private void visit(int data) {
System.out.print(data+"--");
}
//前序遍历
public void preOrder(Node root) {
if(root == null) {
return;
}
visit(root.getData());
preOrder(root.getLeft());
preOrder(root.getRight());
}
//中序遍历
public void inOrder(Node root) {
if(root == null) {
return;
}
inOrder(root.getLeft());
visit(root.getData());
inOrder(root.getRight());
}
//后续遍历
public void afterOrder(Node root) {
if(root == null) {
return;
}
afterOrder(root.getLeft());
afterOrder(root.getRight());
visit(root.getData());
}
}
3、算法实现类(非递归)
public class FindTree2 {
//先序遍历非递归算法
private void preOrder(Node root) {
if(root!=null) {
Stack stack = new Stack();
for (Node node = root; !stack.empty() || node != null;) {
//当遍历至节点位空的时候出栈
if(node == null) {
node = stack.pop();
}
node.visit();
//遍历右孩子存入栈内
if(node.getRightChild()!=null) {
stack.push(node.getRightChild());
}
//遍历左子树节点
node = node.getLeftChild();
}
}
}
//中序遍历的非递归算法
public void inOrder(Node root) {
if(root!=null) {
Stack stack = new Stack();
for (BinaryTree node = root; !stack.empty() || node != null; ) {
//寻找最左的左子树节点,并将遍历的左节点进栈
while(node!=null) {
stack.push(node);
node = node.getLeftChild();
}
if(!stack.empty()) {
node = stack.pop(); //出栈
node.visit(); //读取节点值
node = node.getRightChild();
}
}
}
}
//后序遍历非递归算法
private void postOrder(Node root) {
if(root!=null) {
Stack stack = new Stack();
for (Node node = root; !stack.empty() || node != null;) {
while(root!=null) {
stack.push(root);
root = root.getLeftChild();
}
while(!stack.empty() && root == stack.peek().getRightChild()) {
root = stack.pop();
root.visit();
}
if (stack.empty()) {
return;
} else {
root = stack.peek().getRightChild();
}
}
}
}
}