tree list 互相转换

本人没有亲测过,有问题的话会重新编辑文档,这篇文章里的代码是积分下载换来的,如果涉及侵权联系我。。。。。看到我这边博客的人可以免积分了。。。。。。

import _ from 'lodash'
export function list2JsonTree(data, options) {
  var mainKey = options && options.mainKey || 'id'
  var parentKey = options && options.parentKey || 'parentId'
  var sortKey = options && options.sortKey || 'seq'
  var childListKey = options && options.childListKey || 'children'
  var deleteParentKey = options && options.deleteParentKey || true
  var deleteSortKey = options && options.deleteSortKey || true

  var idItemMap = {}
  _.each(data, one => {
    // 初始化一下children字段
    one[childListKey] = []
    idItemMap[one[mainKey]] = one
  })
  var res = []
  _.each(data, one => {
    if (one[parentKey] && idItemMap[one[parentKey]]) {
      idItemMap[one[parentKey]][childListKey].push(one)
      if(deleteParentKey) {
        delete one[parentKey]
      }
    } else {
      res.push(one)
      if(deleteParentKey) {
        delete one[parentKey]
      }
    }
  })
  // 排序
  return sortJsonTree(res, sortKey, deleteSortKey)
}

export function sortJsonTree(data, key, deleteKey) {
  let res = _.sortBy(data, key)
  if(deleteKey){
    _.each(res, function(one){
      delete one[key]
    })
  }
  _.each(data, function (one) {
    if (one.children) {
      one.children = sortJsonTree(one.children, key, deleteKey)
    }
  })
  return res
}

export function jsonTree2list(data, options, parentId) {
  var mainKey = options && options.mainKey || 'id'
  var parentKey = options && options.parentKey || 'parentId'
  var sortKey = options && options.sortKey || 'seq'
  var childListKey = options && options.childListKey || 'children'
  var deleteChildListKey = options && options.deleteChildListKey || true
  let res = []
  _.each(data, function (one, index) {
    if (parentId) {
      one[parentKey] = parentId
    }
    res.push(one)
    one[sortKey] = index + 1
    if (one[childListKey]) {
      res = res.concat(jsonTree2list(one[childListKey], options, one[mainKey]))
    }
    if(deleteChildListKey) {
      delete one[childListKey]
    }
  })
  return res
}

// let testData = [
//   {id: 1, parentId: 0, name: '1', seq: '2'},
//   {id: 2, parentId: 0, name: '2', seq: '4'},
//   {id: 3, parentId: 0, name: '3', seq: '3'},
//   {id: 4, parentId: 0, name: '4', seq: '1'},
//   {id: 5, parentId: 1, name: '11', seq: '2'},
//   {id: 6, parentId: 1, name: '12', seq: '3'},
//   {id: 7, parentId: 1, name: '13', seq: '1'},
//   {id: 8, parentId: 2, name: '21', seq: '2'},
//   {id: 9, parentId: 2, name: '22', seq: '1'},
// ]
// let a = JSON.stringify(list2JsonTree(testData), 0, 2)
// console.log(a)
// let b = JSON.stringify(jsonTree2list(JSON.parse(a)),0,2)
// console.log(b)-+
### 数据结构中二叉和多叉互相转换的方法 #### 多叉为二叉 为了简化运算并利用已有的高效算法,通常会将多叉(普通转换成二叉。这种转换遵循特定规则: - 将每个节点的第一个子节点作为其左孩子; - 对于每一个兄弟节点链表中的下一个节点视为当前节点的右孩子。 通过这种方式建立起来的新二叉保留了原有多叉的信息层次关系[^1]。 ```python class TreeNode: def __init__(self, value=None): self.value = value self.children = [] def multi_to_binary(root): if not root or not root.children: return None binary_root = BinaryTreeNode(root.value) first_child = multi_to_binary(root.children[0]) if root.children else None sibling = convert_siblings_to_right_children(root.children[1:]) binary_root.left = first_child current = first_child while current and sibling: current.right = sibling.pop(0) current = current.right return binary_root def convert_siblings_to_right_children(siblings): if not siblings: return [] result = [BinaryTreeNode(node.value) for node in siblings] for i in range(len(result)): child_list = siblings[i].children if child_list: result[i].left = multi_to_binary(child_list[0]) return result ``` #### 二叉回多叉 当需要从二叉恢复到原来的多叉表示形式时,可以通过以下过程完成: - 把原来指向第一个孩子的指针当作新创建的多叉里的实际子节点列表的第一项; - 所有原本用来指示右侧同级元素位置的地方现在都变成了新的兄弟节点链接[^4]。 ```python class MultiNode: def __init__(self, value=None): self.value = value self.children = [] def binary_to_multi(binary_node): if not binary_node: return None new_tree_node = MultiNode(binary_node.value) # Convert the left subtree back into a list of children. if binary_node.left is not None: new_tree_node.children.append(binary_to_multi(binary_node.left)) curr_sibling = binary_node.left.right while curr_sibling: new_tree_node.children.append(binary_to_multi(curr_sibling)) curr_sibling = curr_sibling.right return new_tree_node ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值