zoukankan      html  css  js  c++  java
  • [LeetCode] 104. Maximum Depth of Binary Tree ☆(二叉树的最大深度)

    描述

    Given a binary tree, find its maximum depth.

    The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

    Note: A leaf is a node with no children.

    Example:

    Given binary tree [3,9,20,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7

    return its depth = 3.

    解析

    深度优先搜索DFS

    简单的递归。递归条件是,它的最大深度是它左子树的最大深度和右子树最大深度中较大的那个加1。基础条件是,当遇到空节点时,返回深度为0。该递归的实质是深度优先搜索。

    层序遍历

    一层的节点,依次入队列,依次出队列。

    代码

    深度优先搜索DFS

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int maxDepth(TreeNode root) {
            if (null == root) {
                return 0;
            }
            int leftMax = maxDepth(root.left);
            int rightMax = maxDepth(root.right);
            return Math.max(leftMax, rightMax) + 1;
        }
    }

    层序遍历

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int maxDepth(TreeNode root) {
            if (null == root) {
                return 0;
            }
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            int nodeSum = 0;
            while (!queue.isEmpty()) {
                nodeSum++;
                int stackSize = queue.size();
                for (int i = 0; i < stackSize; i++) {
                    TreeNode curNode = queue.poll();
                    if (curNode.left != null) {
                        queue.offer(curNode.left);
                    }
                    if (curNode.right != null) {
                        queue.offer(curNode.right);
                    }
                }
            }
            return nodeSum;
        }
    }
  • 相关阅读:
    (一)python 简单网页爬虫
    环形队列的应用
    AutoResetEvent 和 ManualResetEvent 多线程应用
    委托 和 事件
    Action 和 Func 的用法以及区别
    IIS 配置缓存
    IIS 发布双证书
    函数中返回局部变量的问题
    python函数2-函数参数
    Python基础语法6-冒泡排序
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/10614838.html
Copyright © 2011-2022 走看看