前序遍历:根 左 右
中序遍历:左 根 右
后序遍历:左 右 根
typedef class TreeNode
{
public:
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) { this->val = x; right = NULL; left = NULL; }
}*Tree;
//前序 递归版
void Pre(Tree head)
{
if (head == NULL)
return;
cout << head->val;
Pre(head->left);//左
Pre(head->right);//右
}
//非递归 根 右 左
void Pre2(Tree head)
{
stack<Tree>s;
s.push(head);
while (!s.empty())
{
head = s.top();
cout << s.top()->val;//打印
s.pop();
if (head->right != NULL)
s.push(head->right);
if (head->left != NULL)
s.push(head->left);
}
}
//中序:左根右
void Mid(Tree head)
{
if (head == NULL)
return;
Mid(head->left);
cout << head->val;//打印
Mid(head->right);
}
//中序 非递归 左 根 右
void Mid2(Tree head)
{
stack<Tree>s;
while (!s.empty() || head != NULL)
{
if (head != NULL)
{
s.push(head);
head = head->left;
}
else
{
head = s.top();
cout << head->val;//打印
s.pop();
s.push(head->right);
}
}
}
//后序:左右根
void Last(Tree head)
{
if (head == NULL)
return;
Last(head->left);
Last(head->right);
cout << head->val;
}
//后序:左 右 根、
//因为先序遍历的时候顺序是根左右
//可以借助栈结构在线序遍历的时候,将打印位置保存,然后依次出栈就可以得到左右根
void Last2(Tree head)
{
stack <Tree>s1;
stack<Tree>s2;
s1.push(head);
while (!s1.empty())
{
head = s1.top();
s2.push(s1.top());
s1.pop();
if (head->left!= NULL)
{
s1.push(head->left);
head = head->left;
}
if (head->right != NULL)
{
s1.push(head->right);
head = head->right;
}
}
while (!s2.empty())
{
cout << s2.top();
s2.pop();
}
}