二叉树的非递归和递归遍历

 

Posted by     DH on August 8, 2017

代码

没什么可以说的,代码很简单。

// 递归前序遍历
	public void preOrder1(TreeNode  root){
		if (root != null) {
			System.out.println(root.val);
			preOrder1(root.left);
			preOrder1(root.right);
		}
	}
	
	// 前序遍历非递归
	public void preOrder(TreeNode root){
		
		Stack<TreeNode> stack = new Stack<>();
		
		while (root != null || !stack.isEmpty()) {
			
			while (root != null) {
				System.err.println(root.val);
				stack.push(root);
				root = root.left;
			}
			
			while (!stack.isEmpty()) {
				root =  stack.pop();
				root = root.right;
			}
			
		}
		
		
		
	}
	
	// 中序遍历递归
	public void inOrder1(TreeNode root){
		if (root!= null) {
			inOrder1(root.left);
			System.out.println(root.val);
			inOrder1(root.right);
		}
	}
	
	// 中序遍历非递归
	public void inOder2(TreeNode root){
		
		Stack<TreeNode> stack = new Stack<>();
		
		while (!stack.isEmpty() || root != null) {
			 
			while (root != null) {
				stack.push(root);
				root = root.left;
			}
			
			if (!stack.isEmpty()) {
				root = stack.pop();
				System.out.println(root.val);
				root = root.right;
			}
			
		}
			
		
			
	}
	
	// 后序遍历递归
	public void lateOrder1(TreeNode root) {
		if (root != null) {
			lateOrder1(root.left);
			lateOrder1(root.right);
			System.out.println(root.val);
		}
	}
	
	// 后序遍历的非递归
	public void lateOrder2(TreeNode root){
	
		Stack<TreeNode> stack1 = new Stack<>();
		Stack< TreeNode> tempStack = new Stack<>();
		while (root != null || stack1.isEmpty() == false) {
			while(root != null){
				stack1.push(root);
				tempStack.push(root);
				root = root.right;
			}
			
			if (!stack1.isEmpty()) {
				root = stack1.pop();
				root = root.left;
			}
			
		}
		
		while (tempStack.isEmpty() == true) {
			root = tempStack.pop();
			System.out.println(root.val);
			
		}
		
	}