给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
Java代码:
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new LinkedList<>();
if (null != root) {
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode tmp;
if (null == stack.peek().left && null == stack.peek().right) {
tmp = stack.pop();
result.add(tmp.val);
} else {
tmp = stack.peek();
if (null != tmp.right) {
stack.push(tmp.right);
tmp.right = null;
}
if (null != tmp.left) {
stack.push(tmp.left);
tmp.left = null;
}
}
}
}
return result;
}
}