美文网首页
二叉树的最小深度

二叉树的最小深度

作者: Ag_fronted | 来源:发表于2021-10-16 19:15 被阅读0次

求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。

const binaryTree = {
  root: {
    key: 1,
    left: {
      key: 2,
      left: { key: 3, left: null, right: null },
      right: { key: 4, left: null, right: null },
    },
    // right: {
    //   key: 2,
    //   left: { key: 4, left: null, right: null },
    //   right: { key: 5, left: null, right: null },
    // },
    right: {
      key: 2,
      left: null,
      right: null,
    },
  },
};

##Way1
function run(root) {
  let result = [];
  function findTree(node, index) {
    if (node.left === null && node.right === null) {
      result.push(index + 1);
    }
    if (node.left) findTree(node.left, index + 1);
    if (node.right) findTree(node.right, index + 1);
  }
  if (root) {
    findTree(root, 0);
    console.log(result);
    result.sort();
    return result[0];
  } else {
    return 0;
  }
}

##Way2
function run(root) {
  let result = 10000;
  function findTree(node, index) {
    if (node.left === null && node.right === null) {
      if (index + 1 < result) result = index + 1;
    }
    if (node.left) findTree(node.left, index + 1);
    if (node.right) findTree(node.right, index + 1);
  }
  if (root) {
    findTree(root, 0);
    return result;
  } else {
    return 0;
  }
}

console.log(run(binaryTree.root));

相关文章

  • 111. Minimum Depth of Binary Tre

    题目 给定一个二叉树,求二叉树最小深度 解析 一个二叉树的最小深度,就是求左子树最小深度或者右子树最小深度,然后加...

  • 二叉树面试题基本问题

    二叉树的最大深度与最小深度 二叉树的最大深度 最大深度是指二叉树根节点到该树叶子节点的最大路径长度。而最小深度自然...

  • Swift - LeetCode - 二叉树的最小深度

    题目 二叉树的最小深度 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。...

  • Leetcode 111 二叉树的最小深度

    二叉树的最小深度 题目 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。...

  • 111.二叉树的最小深度

    题目#111.二叉树的最小深度 给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点...

  • LeetCode 111. 二叉树的最小深度(Minimum D

    111. 二叉树的最小深度 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数...

  • [LeetCode]111. 二叉树的最小深度

    111. 二叉树的最小深度给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。...

  • 111. 二叉树的最小深度

    111. 二叉树的最小深度 给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量...

  • 111. 二叉树的最小深度(Python)

    题目 难度:★★☆☆☆类型:二叉树 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上...

  • LeetCode 深度优先遍历

    概述 前言 104 二叉树的最大深度【简单】 111 二叉树的最小深度 【简单】 124 二叉树中的最大路径和 【...

网友评论

      本文标题:二叉树的最小深度

      本文链接:https://www.haomeiwen.com/subject/bpbboltx.html