leetcode
144. 二叉树的前序遍历
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 vector<int> preorderTraversal(TreeNode* root) { 15 vector<int>ans; 16 stack<TreeNode*>st; 17 if(!root)return ans; 18 st.push(root); 19 while(st.size()) 20 { 21 auto p=st.top(); 22 ans.push_back(p->val); 23 st.pop(); 24 if(p->right)st.push(p->right); 25 if(p->left)st.push(p->left); 26 } 27 return ans; 28 } 29 };
94. 二叉树的中序遍历
/** * 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: vector<int> inorderTraversal(TreeNode* root) { vector<int>ans; if(!root)return ans; stack<TreeNode*>st; auto cur=root; while(st.size()||cur) { while(cur) { st.push(cur); cur=cur->left; } auto p=st.top(); st.pop(); ans.push_back(p->val); cur=p->right; } return ans; } };
145. 二叉树的后序遍历
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 vector<int> postorderTraversal(TreeNode* root) { 15 vector<int>ans; 16 if(!root)return ans; 17 stack<TreeNode*>st; 18 TreeNode* pre=nullptr,*cur=root; 19 20 while(st.size()||cur) 21 { 22 while(cur) 23 { 24 st.push(cur); 25 cur=cur->left; 26 } 27 auto p=st.top(); 28 if(!p->right||p->right==pre) 29 { 30 ans.push_back(p->val); 31 st.pop(); 32 pre=p; 33 } 34 else cur=p->right; 35 } 36 return ans; 37 } 38 };