首页 > 代码库 > 二叉树的非递归遍历--中序遍历
二叉树的非递归遍历--中序遍历
package algorithm;
import java.util.Stack;
class TreeNode<T> {
T data;
TreeNode left;
TreeNode right;
public TreeNode(T data, TreeNode left, TreeNode right) {
super();
this.data = http://www.mamicode.com/data;
this.left = left;
this.right = right;
}
public TreeNode(T data){
this.data=http://www.mamicode.com/data;
}
}
public class InOrderTraverse {
public static void inOrderTraverse(TreeNode root) {
Stack stack = new Stack();
while(root != null || !stack.isEmpty()) {
if (root!=null) {
stack.push(root);
root=root.left;
} else {
visit((TreeNode)stack.peek());
root = (TreeNode)stack.pop();
root = root.right;
}
}
}
private static void visit(TreeNode p) {
System.out.println(p.data);
}
public static void main(String[] args) {
TreeNode<Integer> e = new TreeNode<Integer>(5);
TreeNode<Integer> g = new TreeNode<Integer>(7);
TreeNode<Integer> h = new TreeNode<Integer>(8);
TreeNode<Integer> l = new TreeNode<Integer>(12);
TreeNode<Integer> m = new TreeNode<Integer>(13);
TreeNode<Integer> n = new TreeNode<Integer>(14);
TreeNode<Integer> k = new TreeNode<Integer>(11, n, null);
TreeNode<Integer> j = new TreeNode<Integer>(10, l, m);
TreeNode<Integer> i = new TreeNode<Integer>(9, j, k);
TreeNode<Integer> d = new TreeNode<Integer>(4, null, g);
TreeNode<Integer> f = new TreeNode<Integer>(6, h, i);
TreeNode<Integer> b = new TreeNode<Integer>(2, d, e);
TreeNode<Integer> c = new TreeNode<Integer>(3, f, null);
TreeNode<Integer> root = new TreeNode<Integer>(1, b, c);
inOrderTraverse(root);
}
}
二叉树的非递归遍历--中序遍历