簡體   English   中英

通過將測試失敗的樹節點映射到其子節點來修剪樹

[英]Pruning a tree by mapping nodes of tree that fail a test to its children

我在這里的問題建立在我試圖解決的另一個問題上,並收到了關於我有一棵樹的地方的很好的答案

const treeData = [{
  title: '0-0',
  key: '0-0',
  children: [{
    title: '0-0-0',
    key: '0-0-0',
    children: [
      { title: '0-0-0-0', key: '0-0-0-0', children: [] },
      { title: '0-0-0-1', key: '0-0-0-1', children: [] },
      { title: '0-0-0-2', key: '0-0-0-2', children: [] },
    ],
  }, {
    title: '0-0-1',
    key: '0-0-1',
    children: [
      { title: '0-0-1-0', key: '0-0-1-0', children: [] },
      { title: '0-0-1-1', key: '0-0-1-1', children: [] },
      { title: '0-0-1-2', key: '0-0-1-2', children: [] },
    ],
  }, {
    title: '0-0-2',
    key: '0-0-2',
    children: []
  }],
}, {
  title: '0-1',
  key: '0-1',
  children: [
    { title: '0-1-0-0', key: '0-1-0-0', children: [] },
    { title: '0-1-0-1', key: '0-1-0-1', children: [] },
    { title: '0-1-0-2', key: '0-1-0-2', children: [] },
  ],
}, {
  title: '0-2',
  key: '0-2',
  children: []
}];

和葉節點數組:

const leafNodes = ['0-0-1-2', '0-1-0-1', '0-1-0-2']

以前,我只想要一個包含所有葉節點路徑的樹的過濾/修剪副本,但現在我想通過刪除不滿足測試的父節點來進一步修剪它——測試正在它的所有子節點都包含在葉節點列表中。 生成的樹將如下所示:

const pruned = [{
    title: '0-0-1-2',
    key: '0-0-1-2',
    children: []
  },
  {
    title: '0-1-0-1',
    key: '0-1-0-1',
    children: []
  }, {
    title: '0-1-0-2',
    key: '0-1-0-2',
    children: []
  }
]

在這里,鍵為0-0-1的節點將被刪除,因為它的 3 個子節點( 0-0-1-2 )中只有一個包含在葉節點列表中,而子節點包含在葉節點列表中(在此情況下,只有一個)被提升到他們現在刪除的父級的級別。 這將流回已刪除節點的父節點,現在使用鍵0-0 ,因為並非所有子節點都包含在修剪樹中。

同樣的模式也適用於0-1

您可以迭代數組並檢查子節點是否已完成選擇,然后獲取實際節點或僅獲取一些子節點,然后僅獲取子節點。

 function getShort(array, keys) { var result = [], every = true; array.forEach(o => { var children; if (keys.includes(o.key)) return result.push(o); if (!o.children || !o.children.length) return every = false; children = getShort(o.children, keys); if (children.length && children.length === o.children.length) return result.push(o); result.push(...children); every = false; }); return every ? array : result; } const treeData = [{ key: '0-0', children: [{ key: '0-0-0', children: [{ key: '0-0-0-0', children: [] }, { key: '0-0-0-1', children: [] }, { key: '0-0-0-2', children: [] }] }, { key: '0-0-1', children: [{ key: '0-0-1-0', children: [] }, { key: '0-0-1-1', children: [] }, { key: '0-0-1-2', children: [] }] }, { key: '0-0-2', children: [] }] }, { key: '0-1', children: [{ key: '0-1-0-0', children: [] }, { key: '0-1-0-1', children: [] }, { key: '0-1-0-2', children: [] }] }, { key: '0-2', children: [] }], leafNodes = [ '0-0-0-0', '0-0-0-1', '0-0-0-2', // all 0-0-0 all 0-0 '0-0-1-0', '0-0-1-1', '0-0-1-2', // all 0-0-1 all 0-0 '0-0-2', // all 0-0-2 all 0-0 '0-1-0-1', '0-1-0-2' ], short = getShort(treeData, leafNodes); console.log(short);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM