1、建立与数据库中表对应的结构体
//组织节点
struct NODE
{
char nodeName[50];
int nodeId;
int nodeLeft;
int nodeRight;
int nodeParent;
HTREEITEM nodeTreeItem;
};
2、在建立对话框mfc中添加一个树形控件,并分配变量m_nodeTree
在 Cmfc2Dlg::OnInitDialog()中添加如下代码:
vector<NODE> vecNode;来保存从数据库中按照先序遍历来的节点
利用队列来实现,宽度遍历访问,并插入到树形控件当中
// TODO: 在此添加额外的初始化代码
NODE nodeRoot;
strcpy_s(nodeRoot.nodeName, "学校");
nodeRoot.nodeLeft = 1;
nodeRoot.nodeRight = 8;
NODE node1;
strcpy_s(node1.nodeName, "办公室");
node1.nodeLeft = 2;
node1.nodeRight = 5;
NODE node2;
strcpy_s(node2.nodeName, "宣传中心");
node2.nodeLeft = 3;
node2.nodeRight = 4;
NODE node3;
strcpy_s(node3.nodeName, "信息中心");
node3.nodeLeft = 6;
node3.nodeRight = 7;
vecNode.push_back(nodeRoot);
vecNode.push_back(node1);
vecNode.push_back(node2);
vecNode.push_back(node3);
list<int> nodeList;
HTREEITEM hRoot;
HTREEITEM hChild;
//CString sTemp("邯郸");
<span style="white-space:pre"> </span>//根节点建立
CString sTemp(nodeRoot.nodeName);
hRoot = m_nodeTree.InsertItem((sTemp));
vecNode[0].nodeTreeItem = hRoot;
nodeList.push_back(0);
while (!nodeList.empty())
{
//1、读取
int front = nodeList.front();
int childNum = (vecNode[front].nodeRight - vecNode[front].nodeLeft - 1) / 2;//子节点个数
//2、宽度遍历
int i = front + 1;
while (i <= front + childNum)
{
//插入队列
CString sTemp(vecNode[i].nodeName);
hChild = m_nodeTree.InsertItem(sTemp, vecNode[front].nodeTreeItem);//在TreeCtrl中插入节点
vecNode[i].nodeTreeItem = hChild;//保存到vecNode中方便下次调用
nodeList.push_back(i);//插入队列,只需要插入在vector中的下标即可
//下标跳跃
i = i + 1 + (vecNode[i].nodeRight - vecNode[i].nodeLeft - 1) / 2;//跳到下个兄弟节点
}
//最后弹出
nodeList.pop_front();
}