LeetCode 145. Binary Tree Postorder Traversal
考点 | 难度 |
---|---|
Tree | Easy |
题目
Given the root
of a binary tree, return the postorder traversal of its nodes’ values.
思路
和preorder类似,除了把node加到ans
的时候需要倒序。
答案
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> ans = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
if (root == null) return ans;
stack.push(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
ans.addFirst(cur.val);
if (cur.left != null) {
stack.push(cur.left);
}
if (cur.right != null) {
stack.push(cur.right);
}
}
return ans;
}