树的遍历
树的题目
树的结构体
class Node
{
public:
Node(int data)
{
value = data;
left = NULL;
right = NULL;
}
public:
int value;
Node *left;
Node *right;
};
递归先中后序遍历树
//先序递归遍历
void preOrderRecur(Node *head)
{
if (head == NULL)
{
return;
}
cout << head->value << " ";
preOrderRecur(head->left);
preOrderRecur(head->right);
}
//中序递归遍历
void inOrderRecur(Node *head)
{
if (head == NULL)
{
return;
}
inOrderRecur(head->left);
cout << head->value << " ";
inOrderRecur(head->right);
}
//后序递归遍历
void posOrderRecur(Node *head)
{
if (head == NULL)
{
return;
}
posOrderRecur(head->left);
posOrderRecur(head->right);
cout << head->value << " ";
}
非递归先序遍历
void preOrderUnRecur(Node *head)
{
cout << "[pre-order]:";
if (head != NULL)
{
stack<Node*>stack;
stack.push(head);
while (!stack.empty())
{
head = stack.top();
stack.pop();
cout << head->value << " ";
if (head->right != NULL)
{
stack.push(head->right);
}
if (head->left != NULL)
{
stack.push(head->left);
}
}
}
cout << endl;
}
非递归中序遍历
void inOrderUnRecur(Node *head)
{
cout << "[in-order]:";
if (head != NULL)
{
stack<Node*>stack;
while (!stack.empty() || head != NULL)
{
if (head != NULL)
{
stack.push(head);
head = head->left;
}
else {
head = stack.top();
stack.pop();
cout << head->value << " ";
head = head->right;
}
}
}
cout << endl;
}
非递归后序遍历
void posOrderUnRecur(Node *head)
{
cout << "[pos-order]:";
if (head != NULL)
{
stack<Node*>s1;
stack<Node*>s2;
s1.push(head);
while (!s1.empty())
{
head = s1.top();
s1.pop();
s2.push(head);
if (head->left != NULL)
{
s1.push(head->left);
}
if (head->right != NULL)
{
s1.push(head->right);
}
}
while (!s2.empty())
{
cout << s2.top()->value << " ";
s2.pop();
}
}
cout << endl;
}
宽度优先遍历
void widthOrderDisplay(Node *head)
{
if (head == NULL)
{
return;
}
queue<Node*>queue;
queue.push(head);
while (!queue.empty())
{
Node *p = queue.front();
cout << p->value << " ";
queue.pop();
if (p->left != NULL)
{
queue.push(p->left);
}
if (p->right != NULL)
{
queue.push(p->right);
}
}
}
求一颗二叉树的宽度
int getMaxWidth(Node *head)
{
if (head == NULL)
{
return 0;
}
queue<Node*>queue;
map<Node*, int>levelMap;
int nodes = 0;
int clevel = 1;
int maxNodes = 0;
levelMap.insert(make_pair(head, 1));
queue.push(head);
while (!queue.empty())
{
Node *p = queue.front();
queue.pop();
int level = levelMap[p];
levelMap.insert(make_pair(p, level));
if (clevel == level)
{
nodes++;
}
else {
cout << "[level]:" << clevel << " [Nodes]:" << nodes << endl;
maxNodes = maxNodes > nodes ? maxNodes : nodes;
clevel++;
nodes = 1;
}
cout << "Node:" << p->value << " level:" << level << endl;
if (p->left != NULL)
{
queue.push(p->left);
levelMap.insert(make_pair(p->left, level+1));
}
if (p->right != NULL)
{
queue.push(p->right);
levelMap.insert(make_pair(p->right, level+1));
}
}
cout << "level:" << clevel << " Nodes:" << nodes << endl;
maxNodes = maxNodes > nodes ? maxNodes : nodes;
return maxNodes;
}