《leetCode》: Maximum Depth of Binary Tree

来源:互联网 发布:淘宝上的6s官换机真相 编辑:程序博客网 时间:2024/06/05 06:17

题目

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 ;

实现代码如下:

第一个版本

int  maxDepth1(struct TreeNode* root){    if(root==NULL){        return 0;    }    return (maxDepth1(root->left)>maxDepth1(root->right)?maxDepth1(root->left):maxDepth1(root->right))+1;}int maxDepth(struct TreeNode* root) {    //int depthTree=0;    return maxDepth1(root); }

报超时错误,经过分析,原因在于在maxDepth1这个函数中下面这条语句中maxDepth1(root->left)和maxDepth1(root->right)都计算了两次,即没有必要的进行了重复计算;

(maxDepth1(root->left)>maxDepth1(root->right)?maxDepth1(root->left):maxDepth1(root->right))+1;

解决方法:引入两个中间变量进行保存中间结果即可。

更改后的代码如下:

int  maxDepth1(struct TreeNode* root){    if(root==NULL){        return 0;    }    int leftMaxDepth=maxDepth1(root->left);    int rightMaxDepth=maxDepth1(root->right);       return (leftMaxDepth>rightMaxDepth?leftMaxDepth:rightMaxDepth)+1;}int maxDepth(struct TreeNode* root) {    //int depthTree=0;    return maxDepth1(root); }

经过这样的修改后,就成功AC了。

1 0
原创粉丝点击