这个树遍历叫做什么?

时间:2019-10-21 10:14:49

标签: algorithm tree tree-traversal

给出一棵以 A 为根的树

A 
+-- B 
|   +-- C
|   +-- D
+-- E 
    +-- F
    +-- G 

我希望遍历是

C,B,A,D,F,E,G

可以通过从叶子到根的所有路径开始构建

C,B,A
D,B,A
F,E,A
G,E,A

,然后删除所有已经遇到的节点

C,B,A
D
F,E
G

此遍历是否有名称?

2 个答案:

答案 0 :(得分:1)

我不知道名字,但是算法可以像这样:

half-explore:
    inorder style (I mapped the first "read" element to be the left)
    except for the right node: push it to a FIFO

whenever _half-explored_ some node, get the right node to explore from FIFO and half-explore it

  /*
  A 
  +-- B 
  |   +-- C
  |   +-- D
  +-- E 
      +-- F
          +--H
          +--I
      +-- G 
   */
  let m = [];
  m['A'] = ['B','E'];
  m['B'] = ['C','D'];
  m['E'] = ['F','G'];
  m['F'] = ['H','I'];
  function main(id){
      function leftdfs(id, queue=[]){
          if(m[id]){
              leftdfs(m[id][0], queue);
              console.log(id);
              queue.push(m[id][1]);
          }else{
              console.log(id);
          }
      }
      let queue = [id];
      while(queue.length){
          let id = queue.shift();
          leftdfs(id, queue)
      }
  }
  //CBADHFEIG
  main('A');

答案 1 :(得分:1)

我认为没有名字。如您所定义,它不仅限于二叉树(与“有序”不同),还可以用于n元树。

与其他答案一样,我将在此处提供递归实现,但使用单个堆栈:

  1. 将给定节点放在堆栈上
  2. 如果节点有子节点,则对每个子节点递归应用此例程
  3. 如果该节点没有子节点,则从堆栈中弹出并访问所有节点。

该算法的JavaScript实现下面将在下图上运行:

           a 
        /     \
      r         e
    / | \     / | \
   G  h  N   d  i  t  
      |     / \    |
      p    o   L   s

预期遍历将按以下顺序列出节点:“ GraphNodeList”

function traverse(adjacency, id, visit, stack=[]) {
    stack.push(id);
    if (adjacency[id]) {
        for (let child of adjacency[id]) traverse(adjacency, child, visit, stack);
    } else {
        while (stack.length) visit(stack.pop());
    }
}

// Example run
let adjacency = { a: 're', r: 'GhN', h: 'p', e: 'dit', d: 'oL', t: 's' };
traverse(adjacency, 'a', console.log); // log each visited node to console.