/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
maxDepth(root);
return max;
}
// 辅助函数,求最大深度,任意节点所在最长路径等于左子树的最大深度 + 右子树的最大深度
public int maxDepth(TreeNode root) {
// base case
if (root == null) return 0;
int left = maxDepth(root.left);
int right = maxDepth(root.right);
// 获得当前最长路径
max = Math.max(max, left + right);
return Math.max(left, right) + 1;
}
}
相关文章
- 01-05236. Lowest Common Ancestor of a Binary Tree 二叉树的最低公共祖先
- 01-05【Leetcode】1123. Lowest Common Ancestor of Deepest Leaves(二叉树最深叶子结点的公共父节点)
- 01-05LeetCode236. Lowest Common Ancestor of a Binary Tree(二叉树的最近公共祖先)
- 01-05LeetCode(104):二叉树的最大深度
- 01-05leetcode题解:Binary Tree Postorder Traversal (二叉树的后序遍历)
- 01-05LeetCode 145. Binary Tree Postorder Traversal二叉树的后序遍历 (C++)
- 01-05有序二叉树节点的删除
- 01-05hdu2196 树形dp经典|树的直径
- 01-05NC45-实现二叉树的先序、中序和后序遍历
- 01-05二叉树的基本操作【C语言】