单次执行流程中,先递归处理当前节点 u 的左右节点,得到左右子树为根时的“往下”最大路径 l 和 r,两者中的较大值 +1 即是本次执行流程的返回值(+1 的含义是在子路径基础上增加当前节点)。
同时,l + r 则是以当前节点 u 为路径最高点时的路径长度,用此更新全局 ans 即可。
Java 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { intans=0; publicintdiameterOfBinaryTree(TreeNode root) { dfs(root); return ans; } intdfs(TreeNode u) { if (u == null) return0; intl= dfs(u.left), r = dfs(u.right); ans = Math.max(ans, l + r); return Math.max(l, r) + 1; } }
C++ 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public: int ans = 0; intdiameterOfBinaryTree(TreeNode* root){ dfs(root); return ans; } intdfs(TreeNode* u){ if (u == NULL) return0; int l = dfs(u->left), r = dfs(u->right); ans = max(ans, l + r); returnmax(l, r) + 1; } };
Python 代码:
1 2 3 4 5 6 7 8 9 10 11
classSolution: defdiameterOfBinaryTree(self, root: TreeNode) -> int: ans = 0 defdfs(u): nonlocal ans ifnot u: return0 left, right = dfs(u.left), dfs(u.right) ans = max(ans, left + right) returnmax(left, right) + 1 dfs(root) return ans
TypeScript 代码:
1 2 3 4 5 6 7 8 9 10 11
functiondiameterOfBinaryTree(root: TreeNode | null): number { let ans = 0; const dfs = function(u: TreeNode): number { if (!u) return0; const l = dfs(u.left), r = dfs(u.right); ans = Math.max(ans, l + r); returnMath.max(l, r) + 1; }; dfs(root); return ans; };