由于树和二叉树可以相互转换,所以树可采用和二叉树相同的方式构造(left变为firstChild,right变为nextBrother),只是遍历方式(中的层次遍历)不同。
树的层次遍历思想:
利用一个辅助队列,初始只有一个根结点。
当一个结点出队时,其大孩子结点入队,大孩子结点的所有兄弟结点也依次入队。
代码:
template<class T>
void Tree<T>::LevelOrder(TreeNode<T> * t) {
queue<TreeNode<T> * > q;
if (t != NULL) {
TreeNode<T> * p;
q.push(t);
while (!q.empty()) {
p = q.top();
q.pop();
cout << p->getData() << endl;
p = getFirstChild(p);
while (p != NULL) {
q.push(p);
p = getNextBrother(p);
}
}
}
}