Binary Tree Preorder Traversal

easy tree dfs stack

Problem

Return the preorder (root, left, right) traversal of a binary tree's node values.

Inputroot = [1, null, 2, 3]
Output[1, 2, 3]
Emit 1 (root), descend right to 2 (no left subtree), then visit 3.

def preorder_traversal(root):
    if not root: return []
    out, stack = [], [root]
    while stack:
        n = stack.pop()
        out.append(n.val)
        if n.right: stack.append(n.right)
        if n.left:  stack.append(n.left)
    return out
function preorderTraversal(root) {
  if (!root) return [];
  const out = [], stack = [root];
  while (stack.length) {
    const n = stack.pop();
    out.push(n.val);
    if (n.right) stack.push(n.right);
    if (n.left) stack.push(n.left);
  }
  return out;
}
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> out = new ArrayList<>();
        if (root == null) return out;
        Deque<TreeNode> stack = new ArrayDeque<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode n = stack.pop();
            out.add(n.val);
            if (n.right != null) stack.push(n.right);
            if (n.left != null) stack.push(n.left);
        }
        return out;
    }
}
vector<int> preorderTraversal(TreeNode* root) {
    vector<int> out;
    if (!root) return out;
    stack<TreeNode*> st; st.push(root);
    while (!st.empty()) {
        auto* n = st.top(); st.pop();
        out.push_back(n->val);
        if (n->right) st.push(n->right);
        if (n->left) st.push(n->left);
    }
    return out;
}
Time: O(n) Space: O(h)