C++ ✅ || 5 Lines Code 🎯||Beats 100 %💯 || Recursive Approach🔥
Preorder Traversal of a Binary Tree 🌳✨ "Every node in DSA is a step toward mastering the tree of knowledge—keep climbing!" 🌟Intuition 🤔Preorder traversal visits
# Preorder Traversal of a Binary Tree 🌳

# ✨ **"Every node in DSA is a step toward mastering the tree of knowledge—keep climbing!"** 🌟  
![Screenshot 2024-12-25 222635.png](https://assets.leetcode.com/users/images/c1fb4cd2-8a84-4a94-baa1-56febee45bea_1735146293.3581512.png)

---

## Intuition 🤔  
Preorder traversal visits nodes in the order: **Root ➡ Left ➡ Right**. This ensures the root is processed before its subtrees, making it ideal for tasks where the root data is prioritized.

---

## Approach 🚀  
1. Use **recursion** to traverse the tree.  
2. At each step:  
   - Process the **current node** (Root).  
   - Recur for the **left subtree**.  
   - Recur for the **right subtree**.  
3. Collect values in a vector and return it.  

---

## Complexity Analysis 📊  
- **Time complexity:** $$O(n)$$, where $$n$$ is the number of nodes in the tree (each node is visited once).  
- **Space complexity:** $$O(h)$$, where $$h$$ is the height of the tree (due to recursive stack calls).  

---

## Code 💻  
```cpp
class Solution {
public:
    void solve(TreeNode* temp, vector<int>& ans) {
        if (temp == NULL) return;  // Base case
        ans.push_back(temp->val); // Visit root
        solve(temp->left, ans);   // Traverse left subtree
        solve(temp->right, ans);  // Traverse right subtree
    }
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> ans;
        solve(root, ans);
        return ans;
    }
};
```
![upvote.jpeg](https://assets.leetcode.com/users/images/fb69df24-7fa7-4c23-811f-58c20f108bc2_1735146270.8680444.jpeg)

['Tree', 'Binary Tree', 'C++']