【LeetCode】145. Binary Tree Postorder Traversal (3 solutions)
Binary Tree Postorder Traversal
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?
解法一:递归法
/** * 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> ret; Helper(ret, root); return ret; } void Helper(vector<int>& ret, TreeNode* root) { if(root != NULL) { Helper(ret, root->left); Helper(ret, root->right); ret.push_back(root->val); } } };
解法二:借助栈的深度优先搜索,需要记录每个节点是否访问过。
/** * 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> ret; if(root == NULL) return ret; stack<TreeNode*> stk; unordered_map<TreeNode*, bool> visited; stk.push(root); visited[root] = true; while(!stk.empty()) { TreeNode* top = stk.top(); if(top->left != NULL && visited[top->left] == false) { stk.push(top->left); visited[top->left] = true; continue; } if(top->right != NULL && visited[top->right] == false) { stk.push(top->right); visited[top->right] = true; continue; } ret.push_back(top->val); stk.pop(); } return ret; } };
解法三:在Discussion看到一种巧妙的解法。
前序是:根左右
后序是:左右跟
因此可以将前序改为根右左,然后逆序为左右根输出。
前序遍历不需要回溯(对应图的深度遍历),是一种半层次遍历,因此效率很高。
/** * 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> ret; if(root == NULL) return ret; stack<TreeNode*> stk; stk.push(root); while(!stk.empty()) { TreeNode* top = stk.top(); stk.pop(); ret.push_back(top->val); if(top->left != NULL) stk.push(top->left); if(top->right != NULL) stk.push(top->right); } reverse(ret.begin(), ret.end()); return ret; } };