2020年5月13日
LeetCode 104. Maximum Depth of Binary Tree
C++, LeetCode, 算法, 编程
0 Comments
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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
return its depth = 3.
解析:计算二叉树的最大深度。
采用递归的思路,代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
int len = 0;
if(root == NULL)
return len;
int left_len = 0;
int right_len = 0;
if(root->left)
left_len = maxDepth(root->left);
if(root->right)
right_len = maxDepth(root->right);
len += max(left_len, right_len)+1;
return len;
}
};