标签:
先简单介绍下先序遍历、中序遍历和后序遍历,

先序遍历为ABC,中序遍历为BAC,后续遍历为BCA,根节点在的位置决定了什么遍历。
该题的递归解法:
class Solution {
public:
typedef TreeNode * STreeNode;
vector<int> buf;
vector<int> postorderTraversal(TreeNode *root) {
if(root != NULL)
rpostorder(root);
return buf;
}
void rpostorder(TreeNode *root)
{
if(root->left == NULL && root->right == NULL)
{
buf.push_back(root->val);
return ;
}
if(root->left != NULL)
{
rpostorder(root->left);
}
if(root->right != NULL)
{
rpostorder(root->right);
}
buf.push_back(root->val);
}
};
该题的非递归解法:
class Solution {
public:
typedef TreeNode * STreeNode;
vector<int> result;
vector<int> postorderTraversal(TreeNode *root) {
stack<pair<STreeNode,bool>> buf;
if(root == NULL)
return result;
while(1)
{
if(root->left == NULL && root->right == NULL)
{
result.push_back(root->val);
root = GetData(buf);
if(root == NULL)
break;
}
else if(root->left != NULL)
{
buf.push(pair<STreeNode,bool>(root,true));
if(root->right != NULL)
{
buf.push(pair<STreeNode,bool>(root->right,false));
}
root = root->left;
}
else
{
buf.push(pair<STreeNode,bool>(root,true));
root = root->right;
}
}
return result;
}
STreeNode GetData(stack<pair<STreeNode,bool>> &buf)
{
pair<STreeNode,bool> temp;
if(buf.size() == 0)
return NULL;
while(1)
{
temp = buf.top();
buf.pop();
if(temp.second == false)
break;
result.push_back((temp.first)->val);
if(buf.size() == 0)
break;
}
if(temp.second == true)
return NULL;
else
return temp.first;
}
};
Binary Tree Postorder Traversal
标签:
原文地址:http://www.cnblogs.com/xgcode/p/4175706.html