题目
Given a binary tree, return the postorder traversal of its nodes' values.
Note: Recursive solution is trivial, could you do it iteratively?
思路
题目给的Note提示,意思是用非递归实现二叉树的后序遍历
之前用c很详细的描述过二叉树各种递归、非递归遍历,想了解原理的同学移步: http://blog.csdn.net/wzy_1988/article/details/8450952
AC代码
import java.util.ArrayList;
import java.util.LinkedList;
public class BinaryTreePostorderTraversal {
static class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) {
this.val = x;
}
}
public static ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
TreeNode pre = null;
while (!stack.isEmpty() || root != null) {
if (root != null) {
stack.addFirst(root);
root = root.left;
} else {
root = stack.removeFirst();
if (root.right == null || root.right == pre) {
pre = root;
list.add(root.val);
root = null;
} else {
stack.addFirst(root);
root = root.right;
}
}
}
return list;
}
}
后记
二叉树的非递归后序遍历应该算是遍历中还稍微有点难度的,这个看懂了相信非递归前序、中序遍历都不是问题,加油