1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> preorderTraversal(TreeNode* root) { 13 vector<int> res; 14 if(root == NULL) 15 return res; 16 stack<TreeNode*> node; 17 node.push(root); 18 TreeNode *p, *cur; 19 p = root; 20 res.push_back(p->val); 21 while(!node.empty()) 22 { 23 while(p->left != NULL) 24 { 25 p = p->left; 26 res.push_back(p->val); 27 node.push(p); 28 } 29 cur = node.top(); 30 node.pop(); 31 if(cur->right != NULL) 32 { 33 p = cur->right; 34 res.push_back(p->val); 35 node.push(p); 36 } 37 } 38 return res; 39 } 40 };