【问题标题】:Create a Tree/Trie from a word从单词创建树/Trie
【发布时间】:2019-04-16 12:55:32
【问题描述】:

我需要一些帮助来创建一个用单词构建树的 javascript 算法。树的节点是始终按字母顺序排列的单词的字母。前任。 'balance' 应该是这个对象:

  const tree = {
    b: {
      l: {
        n: {}
      },
      n: {}
    },
    a: {
      l: {
        n: {

        }
      },
      n: {

      },
      c: {
        e: {

        }
      },
      e: {

      }
    }
....
  }
}

  const asArray = a.split('')
  const tree = {}
  for (let i = 0; i < a.length; i++) {
    const letter = array[i];
    const greaterThan = asArray.filter((value, index) => {
      return value > letter && index > i
    })
    tree[letter] = {}
    for (let j = 0; j < greaterThan.length; j++) {
      const gt = greaterThan[j];
      tree[letter][gt] = {}
    }
  }

一个javascript对象,键是字母。

【问题讨论】:

  • 这很不寻常。一个词,你只得到一个分支。
  • 是的,我希望balance 产生{b:{a:{l:{a:{n{c:{e:{}}}}}}}} 或类似的东西。生成这个结构的规则是什么?
  • The nodes of the tree are the letters of the word that are always in alphabetical order 以及object keys don't have a guaranteed iteration order 时如何工作?
  • @NinaScholz 实际上每个字母都会产生自己的树。在这种情况下没有单个根节点。对象的第一层有点像树的根。
  • @VLAZ 规则是遍历单词的所有字母,然后从那里开始分支自己的树。好吧,如果对象是嵌套的,我会说顺序无关紧要吗?

标签: javascript algorithm data-structures tree trie


【解决方案1】:

你可以得到所有有序的字符串部分,然后构建树。

function getParts(string) {
    function iter(i, left) {
        var last = left[left.length - 1];
        if (i >= string.length) {
            if (left.length) result.push(left);
            return;
        }
        if (!last || last < string[i] ) iter(i + 1, left.concat(string[i]));
        iter(i + 1, left);
    }

    var result = [];
    iter(0, []);
    return result;
}

var string = 'balance',
    tree = getParts(string).reduce((r, a) => {
        a.reduce((o, k) => o[k] = o[k] || {}, r);
        return r
    }, {});

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

一个完整的递归样式。

function setParts(target, [key, ...values], last = '') {
    if (!key) return;
    if (last < key) setParts(target[key] = target[key] || {}, values, key);
    setParts(target, values, last);
}

var string = 'balance',
    tree = {};

setParts(tree, string);

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 太棒了!但是为什么一个字母不会产生 a : c : e 呢?
猜你喜欢
  • 2017-03-22
  • 1970-01-01
  • 2011-02-17
  • 2020-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-18
相关资源
最近更新 更多