《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
- Leetcode - Tree - Maximum Depth of Binary Tree
- [leetcode][tree] Maximum Depth of Binary Tree
- LeetCode Maximum Depth of Binary Tree
- [Leetcode] Maximum Depth of Binary Tree
- leetcode 24: Maximum Depth of Binary Tree
- [LeetCode] Maximum Depth of Binary Tree
- Leetcode 104 Maximum Depth of Binary Tree
- 【leetcode】Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree
- [LeetCode]Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree
- Leetcode: Maximum Depth of Binary Tree
- LeetCode-Maximum Depth of Binary Tree
- [leetcode] Maximum Depth of Binary Tree
- LeetCode - Maximum Depth of Binary Tree
- LeetCode:Maximum Depth of Binary Tree
- LeetCode | Maximum Depth of Binary Tree
- 【leetcode】Maximum Depth of Binary Tree
- python:split与join
- Unicode字符集的发展历史及与UTF-8,ISO8891-1等字符集的关系
- Android四大组件应用系列——使用BroadcastReceiver和Service实现倒计时
- 大型数据库分析-关联式规则(Associaton-Rules)-2
- Log4j源码解析--Appender接口解析
- 《leetCode》: Maximum Depth of Binary Tree
- sublime text 使用技巧二
- muduo库的学习3---loop基本设计---总论
- 在centos上安装VSFTPD
- Service
- 1081. Rational Sum (20)
- 浅析Java中的final关键字
- 如何做加载状态的监听。
- exe注册成windows服务