LeetCode Maximum Depth of Binary Tree (求树的深度)

时间:2022-05-17 09:13:19

题意:给一棵二叉树,求其深度。

思路:递归比较简洁,先求左子树深度,再求右子树深度,比较其结果,返回:max_one+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) return ;
int a=maxDepth(root->left);
int b=maxDepth(root->right);
return a>b?a+:b+;
}
};

AC代码