# LeetCode 145 Binary Tree Postorder Traversal (后序遍历二叉树)

676人阅读 评论(0)

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?

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {

public void DFS(TreeNode root, List<Integer> ans) {
if(root == null) {
return;
}
DFS(root.left, ans);
DFS(root.right, ans);
}

public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
DFS(root, ans);
return ans;
}
}

/**
* 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> ans = new ArrayList<>();
Stack<TreeNode> stk = new Stack<>();
if(root != null) {
stk.push(root);
}
TreeNode cur = null;
TreeNode pre = null;
while(!stk.empty()) {
cur = stk.peek();
if(cur.left == null && cur.right == null) {
pre = cur;
stk.pop();
}
else if(pre != null && (cur.left == pre || cur.right == pre)) {
pre = cur;
stk.pop();
}
else {
if(cur.right != null) {
stk.push(cur.right);
}
if(cur.left != null) {
stk.push(cur.left);
}
}
}
return ans;
}
}

0
0

个人资料
• 访问：744435次
• 积分：15343
• 等级：
• 排名：第875名
• 原创：818篇
• 转载：7篇
• 译文：0篇
• 评论：123条
博客专栏
 LeetCode 文章：135篇 阅读：78383
 Java学习笔记 文章：10篇 阅读：11284
 算法题 文章：50篇 阅读：34137
阅读排行