题目要求利用迭代算法,也即非递归方法实现二叉树的后序遍历
算法中主要利用了栈
代码
//迭代算法 后序遍历
vector<int> postorderTraversal(TreeNode *root) {
vector<int> res;
stack<TreeNode*> stackTreeNodes;
if(root == NULL)
return res;
stackTreeNodes.push(root);
TreeNode *pre, *cur;
pre = NULL;
cur = root;
while(!stackTreeNodes.empty())
{
cur = stackTreeNodes.top();
if((cur->left==NULL&&cur->right==NULL)||((pre!=NULL)&&(pre == cur->left||pre == cur->right)))
{
res.push_back(cur ->val);
stackTreeNodes.pop();
pre = cur;
}
else
{
if(cur->right!=NULL)
stackTreeNodes.push(cur->right);
if(cur->left!=NULL)
stackTreeNodes.push(cur->left);
}
}
return res;
}
先序与中序的非递归算法如下
//迭代算法 先序遍历
vector<int> preorderTraversal(TreeNode * root)
{
vector<int> res;
stack<TreeNode *>stackTreeNodes;
if(root==NULL)
return res;
TreeNode * cur;
cur = root;
stackTreeNodes.push(root);
while(!stackTreeNodes.empty())
{
cur = stackTreeNodes.top();
res.push_back(cur->val);
stackTreeNodes.pop();
if(cur->right!=NULL)
stackTreeNodes.push(cur->right);
if(cur->left!=NULL)
stackTreeNodes.push(cur->left);
}
return res;
}
//迭代算法 中序遍历
vector<int> inorderTraversal(TreeNode * root)
{
vector<int> res;
stack<TreeNode *> stackTreeNodes;
TreeNode * cur = root;
while(!stackTreeNodes.empty()||cur!=NULL)
{
while(cur!=NULL)
{
stackTreeNodes.push(cur);
cur = cur->left;
}
if(!stackTreeNodes.empty())
{
cur = stackTreeNodes.top();
res.push_back(cur->val);
stackTreeNodes.pop();
cur = cur->right;
}
}
return res;
}