543. 二叉树的直径
最近更新:2025-04-09 | 字数总计:114 | 阅读估时:1分钟 | 阅读量:次
- 解析
- 递归
Problem: 543. 二叉树的直径
解析
递归
求节点的左右高度,即可求出经过该节点的最大路径长

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { private: int res = 0;
public: int diameterOfBinaryTree(TreeNode *root) { height(root); return res; } int height(TreeNode *node) { if (node == nullptr) { return 0; } int lHeight = height(node->left); int rHeight = height(node->right); res = max(res, lHeight + rHeight); return max(lHeight, rHeight) + 1; } };
|