本文为senlie原创,转载请保留此地址:http://blog.youkuaiyun.com/zhengsenlie
Maximum Depth of Binary Tree
Total Accepted: 16605 Total Submissions: 38287Given 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.
题意:求给定的一棵二叉树的最大深度
思路:dfs递归。树的最大深度=max(左子树的最大深度,右子树的最大深度) + 1
复杂度:时间O(n)(因为每个节点都要访问一次),空间O(log n)(因为递归压栈要保存root指针,栈最大为log n)
相关题目: Minimum Depth of Binary Tree
/**
* Definition for binary tree
* 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;
}
};