DFS與BFS的遞歸與迭代實現

問題

咱們常常須要遍歷這樣一種菜單結構:數組

對應的數據結構以下:安全

let list = [{
  text: "A",
  children: [{text: "A1", children: null}, {text: "A2", children: null}]
}, {
  text: "B",
  children: [
    {
      text: "B1",
      children: [
        {text: "B11", children: [{
          text: "B111",
          children: null,
        }, {
          text: "B1112",
          children: null,
        }]}, 
        {text: "B12", children: null}]
    },
    {
      text: "B2",
      children: [{text: "B21", children: null}, {text: "B22", children: null}]
    },

  ]
}, {
  text: "C",
  children: null,
}, {
  text: "D",
  children: [{text: "D1", children: null}, {text: "D2", children: null}]
}];

 

這裏給出幾種實現代碼:數據結構

實現

1.遞歸DFS

 1 /* dfs recursive */
 2 function dfsRecursion(list) {
 3   let result = [];
 4   for(let i=0; i<list.length; ++i) {
 5     result.push(list[i].text);
 6     if(list[i].children) {
 7       result.push(...dfs(list[i].children));
 8     }
 9   }
10   return result;
11 }

 

2.迭代DFS

這裏是使用棧來實現的,這裏有個問題,這樣會修改原來的list,若是是JSON安全的話,spa

能夠先存一份副本:JSON.parse(JSON.stringify(list));而後再進行相應的處理code

/* 
  dfs iteration
  注意這種方式會修改原數組 
*/
function dfsIteration (list) {
  let result = [];
  for(let i=0; i<list.length; ++i) {
    result.push(list[i].text);
    if(list[i].children) {
      list.splice(i+1, 0, ...list[i].children);
    } 
  }
  return result;
}

或者這樣來實現blog

/*
  dfs iteration with stack
*/
function dfsIterationWithStack (list) {
  let result = [];
    stack = [];
  for(let i=0; i<list.length; ++i) {
    result.push(list[i].text);
    if(!list[i].children) {
      continue;
    } else {
      stack.push(...list[i].children.reverse());
    }
    let popItem;
    while(stack.length != 0) {
      popItem = stack.pop();
      result.push(popItem.text);
      popItem.children && stack.push(...popItem.children.reverse());
    }
  }
  return result;
}

 

3.遞歸BFS 

/* bfs recursive */
function bfsRecursion(list) {
  let result = [];
  let children = [];
  for(let i=0; i<list.length; ++i) {
    result.push(list[i].text);
    if(list[i].children) {
      children.push(...list[i].children);
    }
  }
  if(children.length != 0) {           
    return [...result, ...bfs(children)]
  } else {
    return result;
  }
}

 

4.迭代BFS

使用數組收集每一層的元素,直到爲空,也可稱之爲層序遍歷。遞歸

/* 
  bfs iteration
  使用隊列來實現BFS 
*/
function bfsIteration (list) {    
  let result = [],
    children = [];
  while(list.length != 0) {
    for(let i=0; i<list.length; ++i) {
      result.push(list[i].text);
      if(list[i].children) {
        children.push(...list[i].children);
      }
    }
    list = children;
    children = [];
  }
  return result;
}

隊列

相關文章
相關標籤/搜索