<!--
 * @FileDescription: 用JS做二叉树遍历算法
 * https://juejin.cn/post/7028073289943613471
 * @Date: 2023-05-29
 * @LastEditTime: 2023-05-29
-->
<script setup lang="ts">
import { reactive, onMounted } from 'vue';
import Com from 'src/components';

const state = reactive({
  data: {} as any,
});

onMounted(() => {
  getData();
});

/**
 * 我们用js的对象来表示二叉树
 * 对象拥有三个属性，left、value、right,分别是左子树，值和右子树
 * 上面 a+b*(c-d)-e/f 的例子我们用js可以这样表示
 */
function getData() {
  state.data = {
    value: '-',
    left: {
      value: '+',
      left: {
        value: 'a',
      },
      right: {
        value: '*',
        left: {
          value: 'b',
        },
        right: {
          value: '-',
          left: {
            value: 'c',
          },
          right: {
            value: 'd',
          },
        },
      },
    },
    right: {
      value: '/',
      left: {
        value: 'e',
      },
      right: {
        value: 'f',
      },
    },
  };
}
</script>
<template>
  <div>
    <div class="row q-gutter-md">
      <div class="img-box">
        <img src="./imgs/binary-tree.jpg" />
      </div>
      <div class="q-gutter-md">
        <table>
          <thead>
            <tr>
              <th colspan="3">深度遍历</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <th>前序</th>
              <td>先访问根，然后访问左子树，最后访问右子树，DLR</td>
              <td>-+a*b-cd/ef</td>
            </tr>
            <tr>
              <th>中序</th>
              <td>先访问左子树，然后访问根，最后访问右子树，LDR</td>
              <td>a+b*c-d-e/f</td>
            </tr>
            <tr>
              <th>后序</th>
              <td>先后访问左子树，然后访问右子树，最后访问根，LRD</td>
              <td>abcd-*+ef/-</td>
            </tr>
          </tbody>
        </table>

        <table>
          <thead>
            <tr>
              <th colspan="3">广度遍历</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <th>广度</th>
              <td>按层的顺序一层一层遍历</td>
              <td>-+/a*efb-cd</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="q-gutter-md">
        <p>用js表示二叉树</p>
        <Com.JsonView :data="state.data" />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.img-box {
  width: 350px;
  > img {
    width: 100%;
  }
}
table {
  border-collapse: collapse;
  border: 1px solid #0d3f67;
  color: #0d3f67;
  th {
    padding: 6px 4px;
    font-size: 16px;
    min-width: 120px;
    border: 1px solid #0d3f67;
  }
  td {
    padding: 6px 16px;
    font-size: 16px;
    border: 1px solid #0d3f67;
  }
}
</style>
