您的位置:首页 > 其它

[LeetCode]Binary Tree Postorder Traversal,解题报告

2013-12-02 14:49 344 查看

题目

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;
}
}


后记

二叉树的非递归后序遍历应该算是遍历中还稍微有点难度的,这个看懂了相信非递归前序、中序遍历都不是问题,加油
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: