题目链接:https://leetcode.com/problems/binary-tree-postorder-traversal/
题目:
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
解题思路:
二叉树的后序遍历,要借用栈来保存结点。
1. 由于一个结点的左孩子遍历完,和结点左右孩子都遍历完时,都会弹出该结点。
2. 为了区分这两种情况,需要再建立一个标志栈来存储当前结点是否已访问过其左右孩子。
3. 若没有访问过右孩子,将当前结点压栈,走向其右孩子。
4. 若已访问过右孩子,则弹出该结点,并访问它的值。
该题自己写了递归和非递归的形式。还有一种利用线索二叉树的解法,来自于大神,附上其链接:http://blog.youkuaiyun.com/linhuanmars/article/details/22009351
代码实现:
非递归:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList();
if(root == null)
return res;
LinkedList<TreeNode> stack = new LinkedList();
LinkedList<Boolean> flag = new LinkedList();
while(root != null || !stack.isEmpty()) {
if(root == null) {
root = stack.pop();
boolean f = flag.pop();
if(!f) { // 没有访问过右孩子
stack.push(root);
flag.push(true);
root = root.right;
} else { // 已访问过右孩子
res.add(root.val);
root = null;
}
} else {
stack.push(root);
flag.push(false);
root = root.left;
}
}
return res;
}
}
67 / 67 test cases passed.
Status: Accepted
Runtime: 2 ms
递归:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList();
if(root == null)
return res;
helper(root, res);
return res;
}
void helper(TreeNode root, List<Integer> res) {
if(root.left != null)
helper(root.left, res);
if(root.right != null)
helper(root.right, res);
res.add(root.val);
}
}
67 / 67 test cases passed.
Status: Accepted
Runtime: 1 ms