void pre(TreeNode* root)
{
if(NULL == root)
return;
stack<TreeNode*> s;
s.push(root);
while(!s.empty())
{
TreeNode* cur = s.top();
s.pop();
cout << cur->val <<" ";
if(cur->right!=NULL)
s.push(cur->right);
if(cur->left!=NULL)
s.push(cur->left);
}
}
void mid(TreeNode* root)
{
if(NULL == root)
return;
stack<TreeNode*> s;
TreeNode* p = root;
while(p!=NULL || !s.empty())
{
if(p!=NULL)
{
s.push(p);
p = p->left;
}else
{
p = s.top();
s.pop();
cout << p->val << " ";
p = p->right;
}
}
}
void after(TreeNode* root)
{
if(NULL == root)
return;
stack<TreeNode*> s1;
stack<TreeNode*> s2;
s1.push(root);
while(!s1.empty())
{
TreeNode * cur = s1.top();
s2.push(cur);
s1.pop();
if(cur->left!=NULL)
s1.push(cur->left);
if(cur->right!=NULL)
s1.push(cur->right);
}
while(!s2.empty())
{
cout << s2.top()->val<< " ";
s2.pop();
}
}
下面是中序便利的应用
二叉搜索树的第K个结点
题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
即利用非递归的二叉树的中序遍历即可。
/*