Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.ans = 0
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
if root == None:
return 0
self.myPath(root)
return self.ans
def myPath(self, root: Optional[TreeNode]):
if root == None:
return 0
left_path = self.myPath(root.left)
right_path = self.myPath(root.right)
self.ans = self.ans if self.ans > left_path + right_path else left_path + right_path
return 1 + max(left_path, right_path)
Java
法1:自己想的垃圾算法
class Solution {
public int diameterOfBinaryTree(TreeNode root) {
if (root == null) {
return 0;
}
int curDim = maxDepth(root.left) + maxDepth(root.right);
int leftDim = diameterOfBinaryTree(root.left);
int rightDim = diameterOfBinaryTree(root.right);
return Math.max(curDim, Math.max(leftDim, rightDim));
}
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
法2:DFS好方法
和求二叉树中最大路径和相同套路
合理利用全局变量, 可以大大简化问题!!!
class Solution {
int ans = 0;
public int diameterOfBinaryTree(TreeNode root) {
if (root == null) {
return 0;
}
maxDepth(root);
return ans;
}
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
ans = ans > leftDepth + rightDepth ? ans : leftDepth + rightDepth;
return 1 + Math.max(leftDepth, rightDepth);
}
}