Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,2,3]
.
思路:前序遍历,“根,左子树,右子树”
1 #include <iostream> 2 #include <vector> 3 #include <stack> 4 using namespace std; 5 6 struct TreeNode { 7 int val; 8 TreeNode *left; 9 TreeNode *right; 10 TreeNode(int x): val(x), left(NULL), right(NULL) {} 11 }; 12 13 class Solution { 14 public: 15 vector<int> preorderTraversal(TreeNode *root) { 16 vector<int> res; 17 stack<TreeNode*> s; 18 if (!root) { 19 return res; 20 } 21 22 s.push(root); 23 while(!s.empty()) { 24 TreeNode *p = s.top(); s.pop(); 25 res.push_back(p->val); 26 if (p->right) { 27 s.push(p->right); 28 } 29 if (p->left) { 30 s.push(p->left); 31 } 32 } 33 return res; 34 } 35 }; 36 37 int main() { 38 return 0; 39 }