这道题思路很简单,找到左右子树的层数之和然后加一即可,但问题出在我不会表达出函数的递归调用,还有如何更新计数的问题。
class Solution { int ans; int depth(TreeNode* rt){ if (rt == NULL) return 0; // 访问到空节点了,返回0 int L = depth(rt->left); // 左儿子为根的子树的深度 int R = depth(rt->right); // 右儿子为根的子树的深度 ans = max(ans, L + R + 1); // 计算d_node即L+R+1 并更新ans return max(L, R) + 1; // 返回该节点为根的子树的深度 } public: int diameterOfBinaryTree(TreeNode* root) { ans = 1; depth(root); return ans - 1; } };