Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
解題思路:
相比於前序遍歷,后續遍歷思維上難度要大些,前序遍歷是通過一個stack,首先壓入父親結點,然后彈出父親結點,並輸出它的value,之后壓人其右兒子,左兒子即可。然而后序遍歷結點的訪問順序是:左兒子 -> 右兒子 -> 自己。那么一個結點需要兩種情況下才能夠輸出:第一,它已經是葉子結點;第二,它不是葉子結點,但是它的兒子已經輸出過。那么基於此我們只需要記錄一下當前輸出的結點即可。對於一個新的結點,如果它不是葉子結點,兒子也沒有訪問,那么就需要將它的右兒子,左兒子壓入。如果它滿足輸出條件,則輸出它,並記錄下當前輸出結點。輸出在stack為空時結束。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. vector<int> ans; list<TreeNode*> node_list; if(root == NULL) return ans; node_list.push_front(root); TreeNode *head = root; while(!node_list.empty()) { TreeNode *cur = node_list.front(); if(cur -> right == head || cur -> left == head || ((cur -> right == NULL) && (cur -> left == NULL))) { node_list.pop_front(); ans.push_back(cur -> val); head = cur; } else { if(cur -> right != NULL) node_list.push_front(cur -> right); if(cur -> left != NULL) node_list.push_front(cur -> left); } } } };
