赞
踩
一、二叉树的遍历(图片来源于网络)
二叉树的遍历方式分为三种:先序遍历、中序遍历、后序遍历。
二、先序遍历
struct Node//创建节点
{
Node left;
Node right;
int value;
};
void PerOrder(Node head)//遍历节点
{
if (head == NULL)
return;
cout << head->value;
PerOrder(left);
PerOrder(right);
}
三、中序遍历
struct Node//创建节点
{
Node left;
Node right;
int value;
};
void InOrder(Node head)
{
if (head == NULL)
retun;
InOrder(head.left);
cout << head.value<<" ";//若左孩子为空,则输出叶子节点
InOrder(head.right);
}
void InOrder(Node head) { if (head == NULL) return; stack < Node> q; while (!q.empty) { if (head != NULL) { q.push(head); head = head.left; } else if (head == NULL) { head = q.top(); q.pop(); cout << head.value << " ";//若左孩子为空,则输出叶子节点 head = head.right; } } }
四、后序遍历
struct Node
{
Node left;
Node right;
int value;
};
void PostOrder(Node head)
{
if (head == NULL)
return;
PostOrder( head.left);
PostOrder(head.right);
cout << head.value << " ";
}
void PostOrder(Node head) { if (head == NULL) return; stack<Node> q; stack<Node>p; q.push(head); while (!q.empty) { head = q.top(); p.push(head); if (head.left != NULL) q.push(head.left); if (head.right != NULL) q.push(head.right); } while (!p.empty) { cout << p.top().value << " "; p.pop(); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。