【算法16天:Day16】第六章二叉树 LeetCode 二叉树的最大深度(104)

89 阅读1分钟

题目一:

image.png

解法一:(层序遍历、BFS)

解题思路:

  • 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
  • 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数后者节点数(取决于高度从0开始还是从1开始)

二叉树的最大深度,,也就是根节点的高度,也就是求二叉树的最大层数,只需要在层序遍历中,每一层遍历结束就让深度加一即可。

var maxDepth = function(root) {
    if (root === null) return 0
    let queue = [root]
    let deep = 0
    while (queue.length) {
        let length = queue.length // 这里需要将之前队列长度保存下来,因为queue在不断变化
        for (let i = 0; i < length; i++) {
            let node = queue.shift()
            node.left && queue.push(node.left)
            node.right && queue.push(node.right)
        }
        deep++
    }
    return deep
};

解法二:(递归,后序遍历)

  • 确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回这棵树的深度,所以返回值为int类型。

代码如下:js 无返回值

var getdepth = function(node) {}
  • 确定终止条件:如果为空节点的话,就返回0,表示高度为0。

代码如下:

if (node == NULL) return 0;
  • 确定单层递归的逻辑:先求它的左子树的深度,再求的右子树的深度,最后取左右深度最大的数值 再+1 (加1是因为算上当前中间节点)就是目前节点为根节点的树的深度。

代码如下:

let leftdepth = getdepth(node->left);       // 左
let rightdepth = getdepth(node->right);     // 右
let depth = 1 + max(leftdepth, rightdepth); // 中
return depth;

整体代码:

var maxDepth = function(root) {
    if (root === null) return 0
    let left = maxDepth(root.left)
    let right = maxDepth(root.right)
    return Math.max(left, right) + 1
};
// 或者
var maxDepth = function(root) {
    if (root === null) return 0
    let left = 1 + maxDepth(root.left)
    let right = 1 + maxDepth(root.right)
    return Math.max(left, right)
};

解法三:(DFS)

/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function (root) {
  let maxDepth = Number.MIN_SAFE_INTEGER;
  const dfs = (root, depth) => {
    if (root == null) return depth;
    if (root.left == null && root.right == null)
      return (maxDepth = Math.max(depth + 1, maxDepth));
    dfs(root.left, depth + 1);
    dfs(root.right, depth + 1);
  };
  dfs(root, 0);
  return maxDepth == Number.MIN_SAFE_INTEGER ? 0 : maxDepth;
};