Maximum Depth of Binary Tree--LeetCode
2017-09-14 19:30
375 查看
1.题目
Maximum Depth of Binary TreeGiven 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.
2.题意
给定一个二叉树, 找到它的最大深度。最大深度是沿最长路径的节点数,从根节点向下到最远的叶节点。
3.分析
1)递归:采用DFS返回左子树与右子树中较大的深度加1即可时间复杂度 O(n),空间复杂度 O(logn)
2)非递归:采用BFS进行层序遍历,总层数即为二叉树最大深度
使用其他遍历同样需要O(n)的复杂度,但层序遍历更直观
4.代码
1)递归class Solution { public: int maxDepth(TreeNode* root) { if(root == nullptr) return 0; int left = maxDepth(root->left); int right = maxDepth(root->right); return left > right ? left + 1 : right + 1; //return max(maxDepth(root->left), maxDepth(root->right)) + 1; } };
若是写成
if(maxDepth(root->left) > maxDepth(root->right)) return maxDepth(root->left) + 1; else return maxDepth(root->right) + 1;
则会因maxDepth调用次数过多导致Submission Result: Time Limit Exceeded
2)非递归
class Solution { public: int maxDepth(TreeNode* root) { if(root == nullptr) return 0; queue<TreeNode*> q; q.push(root); int level = 0; while(!q.empty()) { ++level; int len = q.size(); for(int i = 0; i < len; ++i) { TreeNode *node = q.front(); q.pop(); if(node->left) q.push(node->left); if(node->right) q.push(node->right); } } return level; } };
相关文章推荐
- Maximum Depth of Binary Tree leetcode
- [leetcode]Maximum Depth of Binary Tree
- LeetCode Maximum Depth of Binary Tree
- LeetCode-Easy刷题(21) Maximum Depth of Binary Tree
- LeetCode Maximum Depth of Binary Tree
- leetcode: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#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_num2_Maximum Depth of Binary Tree
- LeetCode104 - Maximum Depth of Binary Tree
- Leetcode_num2_Maximum Depth of Binary Tree
- [LeetCode] Maximum Depth of Binary Tree dfs,深度搜索