LeetCode Q 145 - Binary Tree Postorder Traversal
Given a binary tree, return the preorder traversal of its nodes’ values.
Follow up: Recursive solution is trivial, could you do it iteratively?
Similar Questions: Inorder Traversal, Preorder Traversal
Solution
Code:
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
Stack<TreeNode> stack = new Stact<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode curr = stack.pop();
res.add(0, curr.val);
if (curr.left != null) stack.push(curr.left);
if (curr.right != null) stack.push(curr.right);
}
return res;
}