二叉树的递归和非递归遍历(java版本)

//二叉树的节点类
public class TreeNode {
	Object key = new Object();
	TreeNode left = null;
	TreeNode right = null;
	TreeNode(Object k){
		key = k;
	}
	TreeNode(Object k, TreeNode l, TreeNode r){
		key = k;
		left = l;
		right = r;
	}
}
import java.util.*;

public class BinaryTree {
	//初始化二叉树
	public TreeNode initTree(){
		TreeNode G = new TreeNode("G", null, null);
		TreeNode H = new TreeNode("H", null, null);
		TreeNode D = new TreeNode("D", G, H);
		TreeNode B = new TreeNode("B", D, null);
		TreeNode I = new TreeNode("I", null, null);
		TreeNode E = new TreeNode("E", null, I);
		TreeNode F = new TreeNode("F", null, null);
		TreeNode C = new TreeNode("C", E, F);
		TreeNode A = new TreeNode("A", B, C);
		return A;
	}
	//二叉树的递归前序遍历
	public void preOrder(TreeNode root){
		if(root!=null){
			System.out.print(root.key);
			preOrder(root.left);
			preOrder(root.right);
		}
	}
	//非递归前序遍历
	public void preOrder2(TreeNode root){
		LinkedList stack = new LinkedList();
		TreeNode p = root;
		while(p!=null||!stack.isEmpty()){
			if(p!=null){
				System.out.print(p.key);
				stack.push(p);
				p = p.left;
			}else{
				TreeNode n = stack.pop();
				p = n.right;
			}
		}
	}
	//递归中序遍历
	public void inOrder(TreeNode root){
		if(root!=null){
			inOrder(root.left);
			System.out.print(root.key);
			inOrder(root.right);
		}
	}
	//非递归中序遍历
	public void inOrder2(TreeNode root){
		LinkedList stack = new LinkedList();
		TreeNode p = root;
		while(p!=null||!stack.isEmpty()){
			//递归的找最左节点保存到栈中
			if(p!=null){
				stack.push(p);
				p = p.left;
			}else{
				TreeNode n = stack.pop();
				System.out.print(n.key);
				p = n.right;
			}
		}
	}
	//递归后序遍历
	public void postOrder(TreeNode root){
		if(root!=null){
			postOrder(root.left);
			postOrder(root.right);
			System.out.print(root.key);
		}
	}
	//非递归后序遍历
	public void postOrder2(TreeNode root){
		LinkedList stack = new LinkedList();
		ArrayList list = new ArrayList();
		TreeNode p = root;
		while(p!=null||!stack.isEmpty()){
			if(p!=null){
				stack.push(p);
				p = p.left;
			}else{
				TreeNode top = stack.peek();
				if(top.right!=null){
					boolean vist = list.contains(top);
					if(vist){
						TreeNode node = stack.pop();
						System.out.print(node.key);
					}else{
						list.add(top);
						p = top.right;
					}
				}else{
					TreeNode node = stack.pop();
					System.out.print(node.key);
				}
			}
		}
	}
	public static void main(String[] args){
		BinaryTree BT = new BinaryTree();
		TreeNode root = BT.initTree();
		BT.preOrder(root);
		System.out.println();
		BT.preOrder2(root);
		System.out.println();
		BT.inOrder(root);
		System.out.println();
		BT.inOrder2(root);
		System.out.println();
		BT.postOrder(root);
		System.out.println();
		BT.postOrder2(root);
	}
}

 

你可能感兴趣的:(Java,数据结构)