给定一个二叉树,返回它的 后序遍历
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [3,2,1]
Java 解题代码
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Deque<TreeNode> stack = new LinkedList<>();
ArrayList<Integer> array = new ArrayList<>();
if (root == null ) {
return array;
}
stack.push(root);
// 访问顺序定为根右左,然后反转数组即可得到后续遍历
while (!stack.isEmpty()) {
TreeNode temp = stack.pop();
array.add(temp.val);
if (temp.left != null) {
stack.push(temp.left);
}
if (temp.right != null) {
stack.push(temp.right);
}
}
Collections.reverse(array);
return array;
}
}