Given a binary tree, return the preorder traversal of its nodes' values.
简单题,递归和迭代都可以解。
1 class Solution { 2 public: 3 vector<int> preorderTraversal(TreeNode *root) { 4 vector<int> val; 5 if(root == NULL) 6 return val; 7 stack<TreeNode *> path; 8 path.push(root); 9 while(!path.empty()){ 10 TreeNode* node = path.top(); 11 path.pop(); 12 val.push_back(node->val); 13 14 if(node->right != NULL) 15 path.push(node->right); 16 if(node->left != NULL) 17 path.push(node->left); 18 } 19 return val; 20 } 21 };