Q: an ordered array is given, need to convert into a balanced binary tree and then BFSly print each level as a D-dimentional linked list
Need to understand list, vector, BFS, recursion, scope of member function, call-by-reference, class, template.
The main method is the linked list form processing.
1: push the given head into the list, then push it into a vector.
2. if the vector is not empty, push all the left/right children of the head into a temporary list, after BFS this level, push the temp list into the previous vector as output.
Here is the source code and output.
// Ch4.4: Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (i.e., if you have a tree with depth D, you’ll have D linked lists).
// based on Hawstein's solution
// and zyli's github
#include
#include
#include
using namespace std;
class BinNode{
public:
int key;
BinNode *parent, *lChild, *rChild;
BinNode(){}
BinNode(int t): key(t), parent(NULL), lChild(NULL), rChild(NULL){}
};
class BTree{
private:
BinNode *m_root;
public:
BTree(): m_root(NULL){}
BTree(BinNode *t): m_root(t){}
BinNode* getRoot() const{return m_root;}
BinNode* balanceTree(BinNode* pnode, BinNode *parent, int *arr, int low, int high){
if(low>high || arr == NULL)
return NULL;
int mid = (low+high)>>1;
pnode = new BinNode(arr[mid]);
pnode->parent = parent;
pnode->lChild = balanceTree(pnode->lChild, pnode, arr, low, mid-1);
pnode->rChild = balanceTree(pnode->rChild, pnode, arr, mid+1, high);
return pnode;
}
void PrintPre(BinNode *pnode)
{
if(pnode == NULL)
return;
cout << pnode->key << " ";
PrintPre(pnode->lChild);
PrintPre(pnode->rChild);
}
vector> BFSlist(BinNode *head){
vector> res;
int level = 0;
list li;
li.push_back(head);
res.push_back(li);
while(!res[level].empty()){
list l;
list::iterator it;
for(it=res[level].begin(); it!=res[level].end(); ++it){
BinNode *n = *it;
if(n->lChild) l.push_back(n->lChild);
if(n->rChild) l.push_back(n->rChild);
}
++level;
res.push_back(l);
}
return res;
}
void print(vector > res){
vector >::iterator vit;
for(vit=res.begin(); vit!=res.end(); ++vit){
list li = *vit;
list::iterator lit;
for(lit=li.begin(); lit!=li.end(); ++lit){
BinNode *n = *lit;
cout<key<<" ";
}
cout<balanceTree(bt->getRoot(), NULL, arr, low, high);
bt = new BTree(proot);
bt->PrintPre(bt->getRoot());
cout << "\nD-dimesion linked list showoff-------\n";
vector> jerry = bt->BFSlist(proot);
bt->print(jerry);
}
/////////////////////////////////////////////////////////////////////////////
/*output:
Executing the program....
$demo
Balanced tree in array format
10 2 1 5 7 15 13 21 22
D-dimesion linked list showoff-------
10
2 15
1 5 13 21
7 22
*/
本文介绍如何将一个有序数组转换为平衡二叉搜索树,并通过广度优先搜索(BFS)逐层输出各节点形成D维链表。涉及知识点包括链表、向量、递归、成员函数作用域、引用调用、类和模板等。源代码示例展示了树的构造过程以及BFS遍历的具体实现。

被折叠的 条评论
为什么被折叠?



