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?
后序遍历二叉树,基础题。采用递归和非递归两种方式。
递归伪代码:
PostTraversal(Bt) {
PostTraversal(Bt->left);
PostTraversal(Bt->right);
Output(Bt);
}
递归代码
/**
* Definition for binary tree
* 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> rslt;
post(root, rslt);
return rslt;
}
void post(TreeNode *root, vector<int> &rslt) {
if(root != NULL) {
post(root->left, rslt);
post(root->right, rslt);
rslt.push_back(root->val);
}
}
};
非递归代码(破坏树结构)
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> path;
if(root==NULL)return path;
stack<TreeNode*> stk;
stk.push(root);
TreeNode* cur = NULL;
while(!stk.empty())
{
cur = stk.top();
if(cur->left ==NULL && cur->right ==NULL)
{
path.push_back(cur->val);
stk.pop();
}else{
if(cur->right)
{
stk.push(cur->right);
cur->right = NULL;
}
if(cur->left)
{
stk.push(cur->left);
cur->left = NULL;
}
}
}
return path;
}
};
非递归代码(不破坏)
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> path;
if(root==NULL)return path;
stack<TreeNode*> stk;
stk.push(root);
TreeNode* cur = NULL;
TreeNode *last = stk.top();
while(!stk.empty())
{
cur = stk.top();
if( (cur->left ==NULL && cur->right ==NULL))
{
path.push_back(cur->val);
last = cur;
stk.pop();
} else if( (cur->left == last || cur->right == last)) {
path.push_back(cur->val);
last = cur;
stk.pop();
}else{
if(cur->right)
{
stk.push(cur->right);
}
if(cur->left)
{
stk.push(cur->left);
}
}
}
return path;
}
};
还有一种方法是改变TreeNode结构,加入一个标记变量visited,如果左右子树入栈使其visited = true,代表左右子树已经处理了。
当在栈中访问该节点时,如果visited = true直接弹出该节点。