迭代实现后序遍历
由于一步步的按照后序遍历的步骤来实现,会有很多难点。非递归的实现方法是通过反转法、访问标记法、Morris法进行实现。其中,相对好理解以及好实现的就是反转法。
反转法:
即我们将后序遍历后的集合进行反转之后,发现得到的顺序即为中右左的遍历顺序。那么实现思路就可以参考前序遍历,只不过先往右子树迭代遍历,然后再遍历左子树。最后将得到的集合进行反转即可,具体实现如下:
public class PostOrderTraversalClone {
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
bt.root = bt.buildBinaryTree();
List<Integer> result = postOrderTraver(bt.root);
System.out.println(result);
}
public static List<Integer> postOrderTraver(TreeNode root) {
ArrayList<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() || root != null) {
while (root != null) {
stack.push(root);
result.add(root.val);
root = root.right;
}
root = stack.pop();
root = root.left;
}
Collections.reverse(result);
return result;
}
}