AcWing 71. 二叉树的深度
原题链接
简单
作者:
Mobu
,
2023-12-11 21:20:48
,
所有人可见
,
阅读 43
二叉树的深度
案例
输入:二叉树[8, 12, 2, null, null, 6, 4, null, null, null, null]如下图所示:
8
/ \
12 2
/ \
6 4
输出:3
深度
/**
* 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 treeDepth(TreeNode* root) {
if(!root) return 0;
return max(treeDepth(root->left),treeDepth(root->right))+1;
}
};
二叉树最大元素值
class Solution {
public:
int maxsize;
int getmax(TreeNode* root) {
maxval(root);
return maxsize;
}
void maxval(TreeNode* root)
{
if(!root) return;
if(root->val>maxsize) maxsize=root->val;//存最大元素
maxval(root->right);
maxval(root->left);
}
};