继续刷LeetCode,第104题,求二叉树的深度。
分析:
使用递归的方法,遍历左右两个孩子节点,判断哪个较大,就返回其加一。
问题:
1、求二叉树的深度的方法。
附上代码:
/**
* 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==nullptr)
return 0;
int lh=maxDepth(root->left);
int rh=maxDepth(root->right);
return lh>rh?lh+1:rh+1;
}
};