题解 | #二叉树的后序遍历#
二叉树的后序遍历
https://www.nowcoder.com/practice/1291064f4d5d4bdeaefbf0dd47d78541
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型vector */ vector<int> postorderTraversal(TreeNode* root) { // write code here vector<int> order; stack<int> rootval; stack<TreeNode*> Node; while(root!=nullptr||!Node.empty()){ if(root!=nullptr){ rootval.push(root->val); Node.push(root); root = root->right; } else{ root = Node.top(); Node.pop(); root = root->left; } } while(!rootval.empty()){ order.push_back(rootval.top()); rootval.pop(); } return order; } private: void postorder(vector<int> &order,TreeNode* root){ if(root == nullptr) return; postorder(order, root->left); postorder(order, root->right); order.push_back(root->val); } };
后序遍历其实可以看成中右左的逆序。就是把中序的左右遍历反一下,将结果存到栈里,再依次弹出打印即可