leetcode104_二叉树的最大深度
2019-10-18 22:35
615 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qieyuan4083/article/details/102633097
一. 简单题,理解清楚递归函数的定义即可.
[code]#include <iostream> #include <algorithm> using namespace std; 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 == NULL) return 0; return max(maxDepth(root->left), maxDepth(root->right)) + 1; } };
二. 还是参考一下大神吧.
作者:LeetCode
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/er-cha-shu-de-zui-da-shen-du-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
1. 看一下递归算法的复杂度分析...
时间复杂度:我们每个结点只访问一次,因此时间复杂度为 O(N),其中 N 是结点的数量。
空间复杂度:在最糟糕的情况下,树是完全不平衡的,例如每个结点只剩下左子结点,递归将会被调用 N 次(树的高度),因此保持调用栈的存储将是 O(N)。但在最好的情况下(树是完全平衡的),树的高度将是log(N)。因此,在这种情况下的空间复杂度将是 O(log(N))。
2. 方法二:迭代
3. 我们还可以在栈的帮助下将上面的递归转换为迭代。
[code]class Solution { public: int maxDepth(TreeNode* root) { stack<pair<TreeNode*, int>> st; if (root != NULL) st.push(make_pair(root, 1)); int depth = 0; while (!st.empty()) { TreeNode* currentNode = st.top().first; int currentDepth = st.top().second; st.pop(); depth = max(depth, currentDepth); if (currentNode->left != NULL) st.push(make_pair(currentNode->left, currentDepth + 1)); if (currentNode->right != NULL) st.push(make_pair(currentNode->right, currentDepth + 1)); } return depth; } };
相关文章推荐
- LeetCode写题历程——104.二叉树的最大深度
- LeetCode 104 二叉树的最大深度
- 【LeetCode】[104] 二叉树的最大深度——“递归”
- LeetCode104--二叉树最大深度
- 【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】
- leetcode之二叉树类之二叉树深度系列-----104/111/110/108/109 二叉树最大/最小深度/AVL树的判断和由有序序列生成(牵扯分治相关,OJ105/106)
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- [LeetCode-104] Maximum Depth of Binary Tree(二叉树最大深度)
- LeetCode 104--二叉树的最大深度
- LeetCode 104 Maximum Depth of Binary Tree(二叉树的最大深度)
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | 深度优先与广度优先深入理解
- leetcode-腾讯精选练习(50 题)python #104 二叉树的最大深度
- leetcode_【104】二叉树的最大深度
- 【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】
- Leetcode 104 python 二叉树的最大深度
- [LeetCode] 104 二叉树最大深度
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- LeetCode 104 二叉树的最大深度
- LeetCode-104.二叉树的最大深度(相关话题:递归)
- 二叉树的最大深度(leetcode-104)