二叉数的深度广度遍历

104 阅读1分钟

深度遍历

1. 前序

  • 前序遍历: 父节点 => 左子树 => 右子数
    function preTreeSort(root) {
      const result = [];
      // 数据具体处理方式
      function sort(node) {
        if (node !== null) {
          // 当前节点
          result.push(node.val);
          if (node.left !== null) {
            result.push(node.left); // 递归找左节点
          }
          if (node.right !== null) {
            result.push(node.right); // 递归找右节点
          }
        }
      }
      sort(root); // 传入根节点
      return result;
    }

2. 中序

  • 中序遍历: 左子数 => 父节点 => 右子数
    function middleSort(root) {
      const result = [];
      function sort(node) {
        if (node !== null) {
          if (node.left !== null) {
            result.push(node.left);
          }
          result.push(node.val);
          if (node.right !== null) {
            result.push(node.right);
          }
        }
      }
      sort(root);
      return result;
    }

3. 后序

  • 后序遍历:左子数 => 右子数 => 父节点
    function afterSort(node) {
      const result = [];
      function sort(node) {
        if (node !== null) {
          if (node.left !== null) {
            result.push(node.left);
          }
          if (node.right !== null) {
            result.push(node.right);
          }
          result.push(node.val);
        }
      }
      sort(root);
      return result;
    }

广度遍历

    function breadth(node) {
      const result = [];
      node.forEach(item => {
        result.push(item.val);
        if (node.length) {
          result.push(node.left);
        }
        if (node.right) {
          result.push(node.eight);
        }
      });

      if (result.lenght) {
        breadth(result);
      }
    }