BFS在二叉树上的应用
二叉树的层次遍历
// 一颗二叉树
1
/ \
2 3
/ \ / \
4 5 6 7
void levelTraverse(BTree tree)
{
queue<BTree> qTree;
if (tree)
{
qTree.push(tree);
}
while (!qTree.empty())
{
BTree curTree = qTree.front();
qTree.pop();
cout << curTree->value << " ";
if (curTree->left)
qTree.push(curTree->left);
if (curTree->right)
qTree.push(curTree->right);
}
cout << endl;
}
void levelTraverse(BTree tree)
{
queue<BTree> qTree;
if (tree)
{
qTree.push(tree);
}
while (!qTree.empty())
{
int size = qTree.size();
for (int i = 0; i < size; i++) {
BTree curTree = qTree.front();
qTree.pop();
cout << curTree->val << " ";
if (curTree->left)
qTree.push(curTree->left);
if (curTree->right)
qTree.push(curTree->right);
}
cout << endl;
}
}
一颗二叉树从右边看,输出可以看到的节点
// 一颗二叉树
1 <-
/ \
2 3 <-
/ \ / \
4 5 6 7 <-
void canSeeNode(BTree tree)
{
queue<BTree> qTree;
if (tree)
{
qTree.push(tree);
}
while (!qTree.empty())
{
cout << qTree.back()->value << " ";
int size = qTree.size();
for (int i = 0; i < size; i++) {
BTree curTree = qTree.front();
qTree.pop();
if (curTree->left)
qTree.push(curTree->left);
if (curTree->right)
qTree.push(curTree->right);
}
}
cout << endl;
}