144. Binary Tree Preorder Traversal , Easy, Tree
iterative
```cpp
class Solution {
public:
vector preorderTraversal(TreeNode* root) {
if (root == nullptr) return {};
vector ans;
stack<TreeNode*> st;
st.push(root);
while (!st.empty()) {
auto top = st.top();
st.pop();
ans.push_back(top -> val);
if (top -> right != nullptr)
st.push(top -> right);
if (top -> left != nullptr)
st.push(top -> left);
}
return ans;
}
};
```
</details>
Recursive
```cpp
class Solution {
public:
vector ans;
void preOrder(TreeNode* root) {
if (root == nullptr) return;
ans.push_back(root -> val);
preOrder(root -> left);
preOrder(root -> right);
}
vector preorderTraversal(TreeNode* root) {
preOrder(root);
return ans;
}
};
```
</details>