给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
后序遍历为左右根,就要保证当前节点的所有左子子树和右子树都遍历完后在遍历自身。
public List<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> visited = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode pre = root;
while(!stack.isEmpty() || root != null) {
while(root != null) {
stack.push(root);
root = root.left;
}
root = stack.peek();
if(root.right == pre || root.right == null) {
stack.pop();
visited.add(root.val);
pre = root;
root = null;
}else
root = root.right;
}
return visited;
}