二叉树的直径-树543-C++
程序员文章站
2022-02-28 06:20:22
...
算法思想:
深度优先搜索
C++
/**
* 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 res = 1;
int nodes_num(TreeNode * root){
if(root == nullptr) return 0;
int l = nodes_num(root->left);
int r = nodes_num(root->right);
res = max(res, l + r + 1);
return max(l, r) + 1;
}
int diameterOfBinaryTree(TreeNode* root) {
nodes_num(root);
return res - 1;
}
};
上一篇: 二叉树的层次遍历-树102-C++
下一篇: 路径总和-树112-C++