(1)前序遍历:根左右
vector<TreeNode*> Node(TreeNode* pRoot)
{
vector<TreeNode*> vec;
stack<TreeNode*> s;
//TreeNode* p;
if(pRoot==NULL)
return vec;
while(!s.empty()||pRoot)
{
while(pRoot!=NULL)//一直遍历到最左的节点
{
vec.push_back(pRoot);//注意这句代码放置的位置:前序中序的不同
s.push(pRoot);
pRoot=pRoot->left;
}
if(!s.empty())
{
pRoot=s.top();
s.pop();
pRoot=pRoot->right;
}
}
return vec;
}
(2)中序遍历:左根右
vector<TreeNode*> Node(TreeNode* pRoot)
{
vector<TreeNode*> vec;
stack<TreeNode*> s;
//TreeNode* p;
if(pRoot==NULL)
return vec;
while(!s.empty()||pRoot)
{
while(pRoot!=NULL)//一直遍历到最左的节点
{
s.push(pRoot);
pRoot=pRoot->left;
}
if(!s.empty())
{
pRoot=s.top();
s.pop();
vec.push_back(pRoot);//注意这句代码放置的位置:前序中序的不同
pRoot=pRoot->right;
}
}
return vec;
}
(3)后序遍历:左右根
vector<TreeNode*> Node(TreeNode* pRoot)
{
vector<TreeNode*> vec;
stack<TreeNode*> s;
TreeNode* pre;//记录上次访问的节点,而pRoot记录当前访问的节点
if(pRoot==NULL)
return NULL;
while(pRoot!=NULL)//一直遍历到最左的节点
{
s.push(pRoot);
pRoot=pRoot->left;
}
while(!s.empty())
{
pRoot=s.top();
s.pop();
//一个根节点被访问的前提是:无右子树或右子树已经被访问过了
if(pRoot->right==NULL || pRoot->right==pre)
{
vec.push_back(pRoot);
pre=pRoot;//更新上次访问的节点
}
else
{
s.push(pRoot);//根节点再次入栈
pRoot=pRoot->right;
while(pRoot!=NULL)
{
s.push(pRoot);
pRoot=pRoot->left;
}
}
}
return vec;
}