题目描述
给定一个二叉树,返回后序遍历的结果。
样例
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
算法1
(Iterative) $O(n)$
iterative solution with recursive thinking.
credit to: https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/45556/Java-simple-and-clean
JAVA 代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Deque<TreeNode> stk = new ArrayDeque<>();
LinkedList<Integer> ans = new LinkedList<Integer>();
if (root == null) return ans;
stk.push(root);
while (!stk.isEmpty()) {
TreeNode cur = stk.pop();
ans.addFirst(cur.val);
if (cur.left != null) stk.push(cur.left);
if (cur.right != null) stk.push(cur.right);
}
return ans;
}
}