使用迭代的版本:
#include <vector> /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: std::vector<int> postorderTraversal(TreeNode *root) { vector<int> result; traversal(result, root); return result; } void traversal(std::vector<int>& result, TreeNode *node) { if (node == NULL) return; traversal(result, node->left); traversal(result, node->right); result.push_back(node->val); } };
不使用迭代的版本(使用栈):
#include <stack> #include <vector> #include <algorithm> /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: // 相当于倒着遍历一遍节点,postorder的输出顺序应该是 (left -> right -> node) // 那我们现在就按照倒叙遍历这颗树并利用栈的性质进行输出 (node -> right -> left) // 每次在遍历的时候都把栈顶元素出栈,相当于得到当前未遍历节点集合的最后一个节点 std::vector<int> postorderTraversal(TreeNode *root) { std::vector<int> result; std::stack<TreeNode *> _stack; if (root == NULL) return result; _stack.push(root); while (!_stack.empty()) { // 出栈当前节点值 TreeNode *cur = _stack.top(); _stack.pop(); result.push_back(cur->val); // 入栈左子节点 TreeNode *left = cur->left; if (left) _stack.push(left); // 入栈右子节点 TreeNode *right = cur->right; if (right) _stack.push(right); } std::reverse(result.begin(), result.end()); return result; } }; #endif // BINARY_TREE_POSTORDER_TRAVERSAL_H