算法-树&二叉树&二叉搜索树

2021-10-12  本文已影响0人  捡了幸福的猪

二叉树

1、二叉树的最小深度

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
const minDepth =(root)  => {
  if (!root) {
    return 0 
  }
  const que =[[root,1]]
  while (que.length) {
    const [node, length]=que.shift();
    if(!node.left && !node.right){
      return length;
    }
    if(node.left)que.push([node.left,length+1])
    if(node.right)que.push([node.right,length+1])
  }
}

时间复杂度:O(n) (n为树的节点数)
空间复杂度:O(n)

上一篇 下一篇

猜你喜欢

热点阅读