二叉樹的後序遍歷順序爲,root->left, root->right, root,所以須要保存根節點的狀態。顯然使用棧來模擬遞歸的過程,可是難點是怎麼從root->right轉換到root。post
1 vector<int> postOrder(TreeNode *root) 2 { 3 vector<int> res; 4 if(root == NULL) return res; 5 6 TreeNode *p = root; 7 stack<TreeNode *> sta; 8 TreeNode *last = root; 9 sta.push(p); 10 while (!sta.empty()) 11 { 12 p = sta.top(); 13 if( (p->left == NULL && p->right == NULL) || (p->right == NULL && last == p->left) || (last == p->right) ) 14 { 15 res.push_back(p->val); 16 last = p; 17 sta.pop(); 18 } 19 else 20 { 21 if(p->right) 22 sta.push(p->right); 23 if(p->left) 24 sta.push(p->left); 25 } 26 27 } 28 29 30 return res; 31 }
方法2:
其實咱們但願棧中保存的從頂部依次是root->left, root->right, root,當符合上面提到的條件時,就進行出棧操做。有一種巧妙的方法能夠作到,先上代碼
1 vector<int> postOrder(TreeNode *root) 2 { 3 vector<int> res; 4 if(root == NULL) return res; 5 6 TreeNode *p = root; 7 stack<TreeNode *> sta; 8 sta.push(p); 9 sta.push(p); 10 while(!sta.empty()) 11 { 12 p = sta.top(); sta.pop(); 13 if(!sta.empty() && p==sta.top()) 14 { 15 if(p->right) sta.push(p->right), sta.push(p->right); 16 if(p->left) sta.push(p->left), sta.push(p->left); 17 } 18 else 19 res.push_back(p->val); 20 } 21 22 return res; 23 }
對於每一個節點,都壓入兩遍,在循環體中,每次彈出一個節點賦給p,若是p仍然等於棧的頭結點,說明p的孩子們尚未被操做過,應該把它的孩子們加入棧中,不然,訪問p。也就是說,第一次彈出,將p的孩子壓入棧中,第二次彈出,訪問p。