• Time:O(n)
• Space:O(h)

## C++

class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
preorder(root, ans);
return ans;
}

private:
void preorder(TreeNode* root, vector<int>& ans) {
if (!root)
return;

ans.push_back(root->val);
preorder(root->left, ans);
preorder(root->right, ans);
}
};

## JAVA

class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
preorder(root, ans);
return ans;
}

private void preorder(TreeNode root, List<Integer> ans) {
if (root == null)
return;

preorder(root.left, ans);
preorder(root.right, ans);
}
}

## Python

class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []

def preorder(root: Optional[TreeNode]) -> None:
if not root:
return

ans.append(root.val)
preorder(root.left)
preorder(root.right)

preorder(root)
return ans

• Time:O(n)
• Space:O(h)

## C++

class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
if (!root)
return {};

vector<int> ans;
stack<TreeNode*> stack{{root}};

while (!stack.empty()) {
root = stack.top(), stack.pop();
ans.push_back(root->val);
if (root->right)
stack.push(root->right);
if (root->left)
stack.push(root->left);
}

return ans;
}
};

## JAVA

class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
if (root == null)
return new ArrayList<>();

List<Integer> ans = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);

while (!stack.isEmpty()) {
root = stack.pop();
if (root.right != null)
stack.push(root.right);
if (root.left != null)
stack.push(root.left);
}

return ans;
}
}

## Python

class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []

ans = []
stack = [root]

while stack:
node = stack.pop()
ans.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)

return ans