【LeetCode】Binary Tree Postorder Traversal
阿新 • • 發佈:2018-12-16
Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[3,2,1]
題解:用非遞迴方式給出二叉樹的後序遍歷序列,正常想法直接用個棧但是後序是L-R-root的順序,用棧push時必須先把Rpush進來再pushL,因為最先彈出的是L,之後要判斷的就是得到棧中的top節點要怎麼判斷此時操作是繼續push還是pop就是關鍵,如果是葉節點直接push,但是如果不是葉節點呢,此時如果不是葉節點那麼其左右節點肯定已經訪問過,可以設定一個set陣列記錄是否訪問過,實際上這道題就是再得到top節點後,看成一個root,因為後序遍歷root是最後的,所以如果你要進行pop操作,左右節點要麼為空要麼都是訪問過的
100%程式碼:
/** * Definition for a binary tree node. * 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) { vector<int> op; stack<TreeNode*> st; if(root == nullptr) return op; unordered_set<TreeNode*> vis; st.push(root); while(!st.empty()){ TreeNode* cur=st.top(); if((vis.find(cur->left)!=vis.end()||!cur->left)&&(vis.find(cur->right)!=vis.end()||!cur->right)) { op.push_back(cur->val); st.pop(); vis.insert(cur); }else{ if(cur->right) st.push(cur->right); if(cur->left) st.push(cur->left); } } return op; } };