首页 > 其他 > 详细

[LeetCode] 104. Maximum Depth of Binary Tree ☆(二叉树的最大深度)

时间:2019-03-28 14:56:36      阅读:112      评论:0      收藏:0      [点我收藏+]

描述

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;
    }
}

 

[LeetCode] 104. Maximum Depth of Binary Tree ☆(二叉树的最大深度)

原文:https://www.cnblogs.com/fanguangdexiaoyuer/p/10614838.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!