【JAVA】二叉树的非递归后序遍历

public List<Integer> postorderTraversal(TreeNode root) {
		System.out.println("后序遍历");
		List<Integer> list = new ArrayList<>();
		if (root != null) {
			/**
			 * 先序遍历只需要一个栈就可以实现的原因是因为先序遍历就是头左右 直接按照入栈的顺序打印即可实现,但是后序遍历是要求左右头
			 * 我们需要将左右节点都打印后才可以打印头节点,我们就需要将头节点存储 并且保存打印的顺序,所以我们需要借助第二个栈来帮助我们
			 */
			Stack<TreeNode> stack = new Stack<>();
			Stack<TreeNode> help = new Stack<>();
			stack.push(root);
			while (!stack.isEmpty()) {
				// 将头节点压入help栈中存储
				TreeNode cur = stack.pop();
				help.push(cur);
				/**
				 * 因为stack栈不是打印的那个栈,所以要想help栈中先打印左子树 stack栈中就要先放入左子树,让右子树先进入help栈
				 */
				if (cur.left != null) {
					stack.push(cur.left);
				}
				if (cur.right != null) {
					stack.push(cur.right);
				}
			}
			while (!help.isEmpty()) {
				// 打印
				list.add(help.pop().val);
			}
		}
		return list;
	}
经验分享 程序员 微信小程序 职场和发展