您的位置:首页 > 其它

[LeetCode] Maximum Depth of Binary Tree

2015-05-31 17:24 323 查看
这道题主要想说明频繁的函数调用时非常耗时的。

/**
* 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) {
if( !root )
return 0;
else{
int maxDepthLeft = maxDepth( root->left );
int maxDepthRight = maxDepth( root->right );
return (maxDepthLeft>maxDepthRight) ? (maxDepthLeft+1) : (maxDepthRight+1);
}
}
};


/**
* 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) {
if( !root )
return 0;
else{
int maxDepthLeft = maxDepth( root->left );
int maxDepthRight = maxDepth( root->right );
return max(maxDepthLeft, maxDepthRight) + 1;
}
}
};


注意两段代码的第19行,第一段代码直接进行判断,第二段代码要调用max函数。执行时间如下图所示:

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