LeetCode Solutions
144. Binary Tree Preorder Traversal
Time: $O(n)$ Space: $O(h)$
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 == nullptr)
return;
ans.push_back(root->val);
preorder(root->left, ans);
preorder(root->right, ans);
}
};
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;
ans.add(root.val);
preorder(root.left, ans);
preorder(root.right, ans);
}
}
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