问题描述
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.
思路分析
最大深度是从二叉树的根结点到其叶子结点最长的路径。给出一棵二叉树,要求返回二叉树的最大深度的长度。
根据动态规划的思想,用递归方式遍历整个二叉树。如果节点存在则count = 1,然后该节点到其叶子节点的最大深度就是其左子子节点或右子结点中最长的一条;如果节点不存在,返回0;
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
int count = 0;
if(root)
count = 1;
else
return count;
count += max(maxDepth(root->left), maxDepth(root->right));
return count;
}
};
时间复杂度:O(n) //n为树的结点数
反思
对于动态规划的认识正在加深,比较顺利的完成。要注意的是递归的结束条件的设置,否则会出现Runtime Error。