0144.cpp (491B)
1 class Solution { 2 public: 3 vector<int> preorderTraversal(TreeNode *root) { 4 if (!root) return {}; 5 6 vector<int> res; 7 stack<TreeNode *> st; 8 st.push(root); 9 while (!st.empty()) { 10 TreeNode *root = st.top(); 11 st.pop(); 12 while (root) { 13 res.push_back(root->val); 14 if (root->right) st.push(root->right); 15 root = root->left; 16 } 17 } 18 return res; 19 } 20 };