二叉树前序、中序、后序遍历

前序遍历

访问顺序:先根节点,再左子树,最后右子树
递归实现:

public void preOrderTraverse1(TreeNode root) {
	if (root != null) {
		System.out.print(root.val + "->");
		preOrderTraverse1(root.left);
		preOrderTraverse1(root.right);
	}
}

非递归实现

public void preOrderTraverse2(TreeNode root) {
	Stack<TreeNode> stack = new Stack<>();
	TreeNode node = root;
	while (node != null || !stack.empty()) {
		if (node != null) {
			System.out.print(node.val + "->");
			stack.push(node);
			node = node.left;
		} else {
			TreeNode tmp = stack.pop();
			node = tmp.right;
		}
	}
}

中序遍历

递归实现

public void inOrderTraverse(TreeNode root) {
	if (root != null) {
		inOrderTraverse(root.left);
		System.out.print(root.val + "->");
		inOrderTraverse(root.right);
	}
}

非递归实现

public void inOrderTraverse(TreeNode root) {
	Stack<TreeNode> stack = new Stack<>();
	TreeNode node = root;
	while (node != null || !stack.isEmpty()) {
		if (node != null) {
			stack.push(node);
			node = node.left;
		} else {
			TreeNode tmp = stack.pop();
			System.out.print(tmp.val + "->");
			node = tmp.right;
		}
	}
}

后序遍历

递归实现

public void postOrderTraverse(TreeNode root) {
	if (root != null) {
		postOrderTraverse(root.left);
		postOrderTraverse(root.right);
		System.out.print(root.val + "->");
	}
}

非递归实现

public void postOrderTravere(TreeNode root){
	TreeNode cur, pre = null;
	Stack<TreeNode> stack = new Stack<>();
	stack.push(root);
	while (!stack.empty()) {
		cur = stack.peek();
		if ((cur.left == null && cur.right == null) || (pre != null && (pre == cur.left || pre == cur.right))) {
			System.out.print(cur.val + "->");
			stack.pop();
			pre = cur;
		} else {
			if (cur.right != null)
				stack.push(cur.right);
			if (cur.left != null)
				stack.push(cur.left);
		}
	}
}

层次遍历

public void levelOrderTraverse(TreeNode root) {
	if (root == null) {
		return;
	}
	Queue<TreeNode> queue = new LinkedList<TreeNode>();
	queue.add(root);
	while (!queue.isEmpty()) {
		TreeNode node = queue.poll();
		System.out.print(node.val + "->");
		
		if (ndoe.left != null) {
			queue.add(node.left);
		}
		if (node.right != null) {
			queue.add(node.right);
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值