您的位置:首页 > 编程语言 > C语言/C++

leetcode笔记:Maximum Depth of Binary Tree

2015-10-17 23:12 369 查看
一. 题目描述

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.

二. 题目分析

这道题和Minimum Depth of Binary Tree一题相似,这个是求最大深度的,就是对二叉树进行递归,然后将子树的最大深度进行返回,最终得到这个树的最大深度。

这个方法的时间复杂度为:
O(n)
,空间复杂度为:
O(logn)


三. 示例代码

// 时间复杂度为O(n),空间复杂度O(logn)
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution
{
public:
int maxDepth(TreeNode* root)
{
if (!root)
{
return 0;
}

int Result = 1;
int Left = maxDepth(root->left);
int Right = maxDepth(root->right);

if (Left * Right)
{
Result += Left < Right? Right : Left;
}
else
{
Result += Right + Left;
}

return Result;
}
};


四. 小结

无。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息