二叉树遍历七种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liuzhixiong_521/article/details/84853020

数结构

public class TreeNode {
	public TreeNode left;
	public TreeNode right;
	int val;	
	...	
}

先序(递归)

public void preOrder(TreeNode root){
	if(root != null){
		System.out.println(root.getVal());
		preOrder(root.getLeft());
		preOrder(root.getRight());
	}
}

先序(非递归)

public void preOrder(TreeNode root){
	Stack<TreeNode> stack = new Stack<TreeNode>();
	TreeNode p = root;
	
	while(!stack.isEmpty() || p != null){
		while(p != null){
			System.out.println(root.getVal());
			stack.push(p);
			p = p.getLeft();
		}
		
		if(!stack.isEmpty()){
			TreeNode pTemp = stack.pop();
			p = pTemp.getRight();
		}
	}
}

中序(递归)

public void inOrder(TreeNode root){
	if(root != null){
		inOrder(root.getLeft());
		System.out.println(root.getVal());
		inOrder(root.getRight());
	}
}

中序(非递归)

public void inOrder(TreeNode root){
	Stack<TreeNode> stack = new Stack<TreeNode>();
	while(!stack.isEmpty() || root != null){
		while(root != null){
			stack.push(root);
			root = root.getLeft();
		}
		if(!stack.isEmpty()){
			root = stack.pop();
			System.out.println(root.getVal());
			root = root.getRight();
		}
	}
}

后序(递归)

public void postOrder(TreeNode root){
	if(root != null){
		postOrder(root.getLeft());
		postOrder(root.getRight());
		System.out.println(root.getVal());
	}
}

后序(非递归)

public static void preOrder(TreeNode root){
	Stack<TreeNode> stack = new Stack<TreeNode>();
	Stack<TreeNode> output = new Stack<TreeNode>();	
	TreeNode node = root;	
	while(!stack.isEmpty() || node != null){
		if(node != null){
			output.push(node);
			stack.push(node);
			node = node.getRight();
		} else {
			node = stack.pop();
			node = node.getLeft();
		}
	}	
	while(output.size() > 0){
		list.add(output.pop().getVal());
	}
}

层次遍历

public void levelOrder(TreeNode root){	
	LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
	queue.add(root);
	while(!queue.isEmpty()){
		TreeNode node = queue.pop();
		System.out.println(root.getVal());
		if(node.getLeft() != null){
			queue.add(node.getLeft());
		}		
		if(node.getRight() != null){
			queue.add(node.getRight());
		}
	}
}

猜你喜欢

转载自blog.csdn.net/liuzhixiong_521/article/details/84853020