题目
分析
用栈来模拟前序遍历,注意右孩子先进左孩子后进,这样出栈顺序就是先左后右!
代码(递归)
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void dfs(TreeNode *root,vector<int> &res){ if(root == NULL) return; res.push_back(root->val);//对根的处理 dfs(root->left,res); dfs(root->right,res); } vector<int> preorderTraversal(TreeNode* root) { vector<int>res; dfs(root,res); return res; } };
代码(非递归)
1 class Solution { 2 public: 3 vector<int> preorderTraversal(TreeNode* root) { 4 stack<TreeNode*>s; 5 vector<int>res; 6 s.push(root); 7 while(!s.empty()){ 8 auto t = s.top(); 9 s.pop(); 10 if(t!=NULL){ 11 res.push_back(t->val); 12 }else continue; 13 if(t->right!=NULL) s.push(t->right); 14 if(t->left!=NULL) s.push(t->left); 15 } 16 return res; 17 } 18 };