http://oj.leetcode.com/problems/binary-tree-inorder-traversal/
1 vector<int> inorderTraversal(TreeNode *root) { 2 stack<TreeNode *> nextstep; 3 vector<int> res; 4 TreeNode *p=root; 5 TreeNode *DIRTY = new TreeNode(0); 6 bool isMid = true; 7 while(p){ 8 if(p->right && isMid) {nextstep.push(p->right);} 9 10 if(p == DIRTY){ 11 p = nextstep.top(); 12 isMid = (p == DIRTY)?false:true; 13 nextstep.pop(); 14 } 15 if(p->left && isMid){ 16 nextstep.push(p); 17 nextstep.push(DIRTY); 18 p = p->left; 19 } 20 else{ 21 if(p) 22 res.push_back(p->val); 23 if(nextstep.size()>0){ 24 p = nextstep.top(); 25 isMid = (p == DIRTY)?false:true; 26 nextstep.pop(); 27 if(!isMid){ 28 p = nextstep.top(); 29 nextstep.pop(); 30 } 31 } 32 else{ 33 break; 34 } 35 } 36 } 37 delete DIRTY; 38 return res; 39 }
=发现二叉树跟栈,队列这些数据结构的东西,真是可以完美结合。
#相信还有更好的办法,也许我下次再写这道题,就会更好。