您的位置:首页 > 其它

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;
}
};

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