https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
题目:求二叉树高度。
思路:直接遍历,找到一个叶子节点,更新最大值。
class Solution {
public:
int sum=0;
void dfs(TreeNode *root,int i)
{
if(!root->left&&!root->right)
{
sum=sum>i?sum:i;
return ;
}
if(root->left)
dfs(root->left,i+1);
if(root->right)
dfs(root->right,i+1);
return ;
}
int maxDepth(TreeNode* root) {
if(!root) return 0;
dfs(root,1);
return sum;
}
};