LeetCode-104:Maximum Depth of Binary Tree

来源:互联网 发布:淘宝里怎么打开链接 编辑:程序博客网 时间:2024/05/16 12:49

原题描述如下:

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.

Subscribe to see which companies asked this question

题意给定一个二叉树,找出该树丛根节点到叶子节点深度的最大值

解题思路:递归求解。

Java代码:

public class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null)return 0;
        int leftdepth = maxDepth(root.left);
        int rightdepth = maxDepth(root.right);
        
        return leftdepth > rightdepth ? leftdepth+1 : rightdepth+1;
    }
}

0 0
原创粉丝点击