先序遍历递归和非递归解法
1 //前序遍历 2 //递归写法 3 /** 4 * Definition for a binary tree node. 5 * struct TreeNode { 6 * int val; 7 * TreeNode *left; 8 * TreeNode *right; 9 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 void preorder(TreeNode *root,vector<int> &res){ 15 if(root==NULL) return; 16 res.push_back(root->val); 17 preorder(root->left,res); 18 preorder(root->right,res); 19 } 20 vector<int> preorderTraversal(TreeNode* root) { 21 vector<int> res; 22 preorder(root,res); 23 return res; 24 } 25 };
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) return res; 15 stack<TreeNode*> st; 16 st.push(root); 17 while(!st.empty()){ 18 auto node=st.top(); 19 res.push_back(node->val); 20 st.pop(); 21 if(node->right!=NULL) st.push(node->right); 22 if(node->left!=NULL) st.push(node->left); 23 } 24 return res; 25 } 26 };