二叉树遍历七种方式

数结构

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());
		}
	}
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页
实付 9.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值