树的遍历之----先序,中序,后序和层序遍历

1先序、中序、后序遍历(递归实现)

先序遍历:中 左 右
中序遍历:左 中 右
后序遍历:左 右 中

public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int data) {
			this.value = data;
		}
	}
//递归--先序
	public static void preOrderRecur(Node head){
		if(head == null){
			return ;
		}
		System.out.print(head.value + " ");
		preOrderRecur(head.left);
		preOrderRecur(head.right);
	}
	//递归--中序
	public static void inOrderRecur(Node head){
		if(head == null){
			return;
		}
		inOrderRecur(head.left);
		System.out.print(head.value + " ");
		inOrderRecur(head.right);
	}
	//递归--后序
	public static void posOrderRecur(Node head){
		if(head == null){
			return ;
		}
		posOrderRecur(head.left);
		posOrderRecur(head.right);
		System.out.print(head.value + " ");
	}

2先序,中序,后序遍历(非递归)

//非递归--先序 :先压右子节点,再压左子节点
	public static void preOrderUnRecur(Node head){
		if(head != null){
			Stack<Node> stack = new Stack<Node>();
			stack.push(head);
			while(!stack.isEmpty()){
				head = stack.pop();//将根结点压入栈
				System.out.print(head.value + " ");//打印当前节点的值
				if(head.right != null){
					stack.push(head.right);
				}
				if(head.left != null){
					stack.push(head.left);
				}
			}
		}
		System.out.println();
	}
	//非递归--中序
	public static void inOrderUnRecur(Node head){
		if(head != null){
			Stack<Node> stack = new Stack<Node>();
			while(!stack.isEmpty() || head != null){
				if(head != null){
					stack.push(head);
					head = head.left;
				}else {
					head = stack.pop();
					System.out.print(head.value + " ");
					head = head.right; 
				}
			}
		}
		System.out.println();
	}
	
	//非递归--后序:顺序为左右中
	//思路:可先求“中右左”再逆序即可得到“左右中”,参考先序遍历的“中左右”要求“中右左”,只需变换压栈顺序即可
	public static void posOrderUnRecur(Node head){
		if(head != null){
			Stack<Node> s1 = new Stack<Node>();
			Stack<Node> s2 = new Stack<Node>();
			s1.push(head);
			while(!s1.isEmpty()){
				head = s1.pop();
				s2.push(head);
				if(head.left != null){
					s1.push(head.left);
				}
				if(head.right != null){
					s1.push(head.right);
				}
			}
			while(!s2.isEmpty()){
				System.out.print(s2.pop().value + " ");
			}
		}
		System.out.println();
	}

3 层序遍历

//层序遍历(用队列实现,故而没有递归方式)
	public static void levelOrder(Node head){
		if(head == null){
			return;
		}
		Queue<Node> queue = new LinkedList<>();
		queue.offer(head);
		while(!queue.isEmpty()){
			head = queue.poll();
			System.out.print(head.value + " ");
			if(head.left != null){
				queue.offer(head.left);
			}
			if(head.right != null){
				queue.offer(head.right);
			}
		}
	}

猜你喜欢

转载自blog.csdn.net/Felix_ar/article/details/83445519