# Redis: 实现树形数据结构

实现树形数据结构

一次获取所有子节点

id: root, name: Root

id: 1, name: Node1

id: 11, name: Node11

id: 111, name: Node111

id: 112, name: Node112

id: 12, name: Node12

id: 2, name: Node2

id: 21, name: Node21

id: 22, name: Node22

hmset tree:root name "Root" path ""

hmset tree:1 name "Node1" path "root"

hmset tree:11 name "Node11" path "root,1"

hmset tree:111 name "Node111" path "root,1,11"

hmset tree:112 name "Node112" path "root,1,11"

hmset tree:12 name "Node12" path "root,1"

hmset tree:2 name "Node2" path "root"

hmset tree:21 name "Node21" path "root,2"

hmset tree:22 name "Node22" path "root,2"

SORT tree:root:heirs BY n/a GET tree:*->name GET tree:*->path

SORT tree:1:heirs BY n/a GET tree:*->name GET tree:*->path

SORT tree:11:heirs BY n/a GET tree:*->name GET tree:*->path

SORT tree:2:heirs BY n/a GET tree:*->name GET tree:*->path

// 检查子节点

SMEMBERS tree:111:heirs         // 没有子节点

// 删除上级节点的引用

HGET tree:111 path              // root,1,11

SREM tree:root:heirs 111

SREM tree:1:heirs 111

SREM tree:11:heirs 111

// 删除自己

DEL tree:111

// 检查子节点

SMEMBERS tree:111:heirs         // 112

// 删除子节点 ... 参见删除节点 111

// 删除上级节点的引用

HGET tree:11 path               // root,1

SREM tree:root:heirs 11

SREM tree:1:heirs 11

// 删除自己

DEL tree:111