LeetCode - Maximum Depth of Binary Tree

题注

我的一个好朋友,Guangyao Miao,当然啦,以前是高中的同班同学,给我推荐了LeetCode这个Online Judge。相比很多第三方的算法测试平台,这个平台我感觉是最友好的,而且很像Coursera给我感觉,有一种大家在一起学习的意思呢。希望能在毕业之前把所有的题目都刷完,毕竟作为一个Cryptographer,不能总是弄那些很理论的东西嘛,得接地气。

第一个题很简单了。

题目

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.

分析

这是一个很简单的递归题目,大致思路是:

1、如果一个节点是null,那么返回这个节点的depth为0;

2、考察一个节点的左节点和右节点的depth;

3、比较左右节点的depth,取最大值maxDepth,此节点的depth是maxDepth + 1;

确实很简单的思路。

代码

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null){
            return 0;
        }
        int depthLeft = maxDepth(root.left);
        int depthRight = maxDepth(root.right);
        int depth = 0;
        if (depthLeft >= depthRight){
            depth = depthLeft + 1;
        }else{
            depth = depthRight + 1;
        }
        return depth;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值