Question 16th:
Question (Microsoft ):
Enter a binary tree, print each node of the tree from top to bottom, and print the tree from left to right in the same layer.
For example, enter
8
/\
6 10
/\/\
5 7 9 11
Output 8 6 10 5 7 9 11.
[Cpp] view plaincopyprint? # Include <iostream>
# Include <iomanip>
Using namespace std;
Struct BTreeNode
{
Int m_Value;
BTreeNode * m_pLeft;
BTreeNode * m_pRight;
};
Template <typename T>
Struct Node
{
T data;
Node * next;
};
Template <typename T>
Class Myqueue
{
Public:
Myqueue (): front (NULL), rear (NULL ){}
~ Myqueue ()
{
// Node <T> * p;
While (! Empty ())
{
Dequeue ();
}
}
Bool empty ()
{
If (NULL = rear)
Return true;
Else
Return false;
}
Void enqueue (T t)
{
Node <T> * p = new Node <T>;
P-> data = t;
P-> next = NULL;
If (empty ())
{
Rear = front = p;
}
Else
{
Rear-> next = p;
Rear = p;
}
}
T dequeue ()
{
T temp = front-> data;
If (front = rear)
{
Delete front;
Rear = front = NULL;
}
Else
{
Node <T> * p = front;
Front = front-> next;
Delete p;
}
Return temp;
}
Private:
Node <T> * front;
Node <T> * rear;
};
Void print (BTreeNode * t)
{
If (NULL = t)
Return;
Myqueue <BTreeNode *> MQ;
MQ. enqueue (t );
BTreeNode * TNode;
While (! MQ. empty ())
{
TNode = MQ. dequeue ();
Cout <TNode-> m_Value <"";
If (TNode-> m_pLeft! = NULL)
MQ. enqueue (TNode-> m_pLeft );
If (TNode-> m_pRight! = NULL)
MQ. enqueue (TNode-> m_pRight );
}
}
Int main ()
{
System ("pause ");
Return 0;
}
# Include <iostream>
# Include <iomanip>
Using namespace std;
Struct BTreeNode
{
Int m_Value;
BTreeNode * m_pLeft;
BTreeNode * m_pRight;
};
Template <typename T>
Struct Node
{
T data;
Node * next;
};
Template <typename T>
Class Myqueue
{
Public:
Myqueue (): front (NULL), rear (NULL ){}
~ Myqueue ()
{
// Node <T> * p;
While (! Empty ())
{
Dequeue ();
}
}
Bool empty ()
{
If (NULL = rear)
Return true;
Else
Return false;
}
Void enqueue (T t)
{
Node <T> * p = new Node <T>;
P-> data = t;
P-> next = NULL;
If (empty ())
{
Rear = front = p;
}
Else
{
Rear-> next = p;
Rear = p;
}
}
T dequeue ()
{
T temp = front-> data;
If (front = rear)
{
Delete front;
Rear = front = NULL;
}
Else
{
Node <T> * p = front;
Front = front-> next;
Delete p;
}
Return temp;
}
Private:
Node <T> * front;
Node <T> * rear;
};
Void print (BTreeNode * t)
{
If (NULL = t)
Return;
Myqueue <BTreeNode *> MQ;
MQ. enqueue (t );
BTreeNode * TNode;
While (! MQ. empty ())
{
TNode = MQ. dequeue ();
Cout <TNode-> m_Value <"";
If (TNode-> m_pLeft! = NULL)
MQ. enqueue (TNode-> m_pLeft );
If (TNode-> m_pRight! = NULL)
MQ. enqueue (TNode-> m_pRight );
}
}
Int main ()
{
System ("pause ");
Return 0;
}
Use a queue to print the values of each node in the tree from top to bottom from left to right.