LeetCode算法解题集:Maximum Depth of Binary Tree
题目:
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.
思路:
该题目是求二叉树的最大深度,分析每个节点的规律可发现明显的规律,每个节点都有左右之分,依次去求左右节点的深度即可求其最大深度。使用递归法求解。复杂度为:O(n)
代码:
/**
- 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) {
if( root == NULL )
{
return 0;
}
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return max(leftDepth, rightDepth) + 1;
}
};
总结:
1、对于有规则的循环嵌套可以使用迭代法
2、递归法要有一个终结点,找到适当的终结点即可。如该题是 root == NULL 终结掉