二叉树非递归遍历方法小结
二叉树的遍历是面试中经常考察的,其实前中后三种顺序的遍历都大同小异,自己模拟两个栈用笔画画我相信是不难写出代码的。现罗列如下,均是自己所写已通过leetcode。
1 class Solution { 2 public: 3 vector<int> preorderTraversal(TreeNode *root) { 4 vector<int> out; 5 stack<TreeNode*> s; 6 s.push(root); 7 while(!s.empty() && root){ 8 TreeNode *node = s.top(); 9 out.push_back(node->val); 10 s.pop(); 11 if(node->right) s.push(node->right); 12 if(node->left) s.push(node->left); 13 } 14 return out; 15 16 17 } 18 vector<int> inorderTraversal(TreeNode *root) { 19 stack<TreeNode *> s; 20 vector<int> out; 21 TreeNode *node = root; 22 bool done = false; 23 while(!done){ 24 if(node){ 25 s.push(node); 26 node = node->left; 27 }else { 28 if(s.empty()) done = true; 29 else{ 30 node = s.top(); 31 s.pop(); 32 out.push_back(node->val); 33 node = node->right; 34 } 35 } 36 } 37 return out; 38 } 39 vector<int> postorderTraversal(TreeNode *root) { 40 vector<int> out; 41 stack<TreeNode*> s; 42 TreeNode* node = root; 43 s.push(node); 44 while(!s.empty()&&node){ 45 node = s.top(); 46 out.push_back(node->val); 47 s.pop(); 48 if(node->left) s.push(node->left); 49 if(node->right)s.push(node->right); 50 } 51 reverse(out.begin(),out.end()); 52 return out; 53 } 54 };