基础的广度遍历和深度遍历

41 阅读1分钟

面试笔试题遇到,工作中遇到。

当有无限children。。。

<template>
  <div>
    <!-- 使用广度优先遍历修改label -->
    <button @click="updateLabelsBreadthFirst">广度优先修改label</button>
    <!-- 使用深度优先遍历修改label -->
    <button @click="updateLabelsDepthFirst">深度优先修改label</button>
    <!-- 展示修改后的options -->
    <pre>{{ options }}</pre>
  </div>
</template>

<script>
export default {
  data() {
    return {
      options: [{
        value: 'zhinan',
        label: '指南',
        children: [{
          value: 'shejiyuanze',
          label: '设计原则',
          children: [{
            value: 'yizhi',
            label: '一致'
          }, {
            value: 'fankui',
            label: '反馈'
          }, {
            value: 'xiaolv',
            label: '效率'
          }, {
            value: 'kekong',
            label: '可控'
          }]
        }]
      }]
    };
  },
  methods: {
    // 广度优先遍历修改label
    updateLabelsBreadthFirst() {
      this.options.forEach(option => {
        const queue = [option];
        while (queue.length > 0) {
          const node = queue.shift();
          node.label += ' (修改)';
          if (node.children) {
            queue.push(...node.children);
          }
        }
      });
    },
    // 深度优先遍历修改label
    updateLabelsDepthFirst() {
      const traverse = (node) => {
        node.label += ' (修改)';
        if (node.children) {
          node.children.forEach(child => traverse(child));
        }
      };
      this.options.forEach(option => traverse(option));
    }
  }
};
</script>

2024.03.29_

image.png