leetcode 145
二叉树后序遍历: 左->右->根
入栈顺序为根-左-右
出栈顺序为根-右-左 所以需要从头插入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
class Solution { public: vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode *> s; if(root) s.push(root); while(!s.empty()) { TreeNode *temp = s.top(); res.insert(res.begin(), temp->val); s.pop(); if(temp->left) s.push(temp->left); if(temp->right) s.push(temp->right); } return res; } private: vector<int> res; };
|