在前端開發中,我們經常需要根據JSON數據來生成目錄樹以便于用戶瀏覽和操作。借助C語言的強大功能,我們可以輕松地完成這一任務。
#include <stdio.h> #include <stdlib.h> #include <string.h> struct TreeNode { char* name; struct TreeNode* child; struct TreeNode* sibling; }; struct TreeNode* createNode(char* name) { struct TreeNode* node = (struct TreeNode*) malloc(sizeof(struct TreeNode)); node->name = strdup(name); node->child = NULL; node->sibling = NULL; return node; } void addChild(struct TreeNode* parent, struct TreeNode* child) { if (parent->child == NULL) { parent->child = child; } else { struct TreeNode* sibling = parent->child; while (sibling->sibling != NULL) { sibling = sibling->sibling; } sibling->sibling = child; } } void printTree(struct TreeNode* root, int depth) { if (root == NULL) { return; } for (int i = 0; i < depth; i++) { putchar(' '); } printf("%s\n", root->name); printTree(root->child, depth + 2); printTree(root->sibling, depth); } int main() { // JSON數據 char* json = "{ 'name': 'root', 'children': [{ 'name': 'child1', 'children': [] }, { 'name': 'child2', 'children': [{ 'name': 'grandchild1', 'children': [] }, { 'name': 'grandchild2', 'children': [] }] }] }"; // 根據JSON數據創建目錄樹 struct TreeNode* root = createNode("root"); struct TreeNode* child1 = createNode("child1"); struct TreeNode* child2 = createNode("child2"); struct TreeNode* grandchild1 = createNode("grandchild1"); struct TreeNode* grandchild2 = createNode("grandchild2"); addChild(root, child1); addChild(root, child2); addChild(child2, grandchild1); addChild(child2, grandchild2); // 輸出目錄樹 printTree(root, 0); return 0; }
以上代碼演示了如何根據JSON數據來創建一棵目錄樹,并使用遞歸遍歷算法將其輸出。我們先將JSON數據解析成一個結構體,然后遞歸地遍歷結構體中的子節點,逐層縮進并輸出其名稱。