【Leetcode长征系列】Maxmium 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.


这道题挺简单的,我的想法便是,对树进行递归计算高度。

如果是一棵有两个儿子的树,分别返回两个子树的高度,再加上自己已有的高度便是答案;

如果一个结点只有一个树,同样返回两个子树的高度,但为了防止出错,我们在前面会判断传递进来的节点是否为NULL,如果为NULL返回0;

如果是叶子节点,那么直接返回1

代码如下:

#include<iostream>
#include <algorithm>
/*definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    int maxDepth(TreeNode *root) {
        int count=1;
        if (root==NULL) return 0;
        if (root->right!=NULL || root->left!=NULL)
                count = count + max(maxDepth(root->right),maxDepth(root->left));
        else count = 1;
        return count;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值