LeetCode 543. Diameter of Binary Tree
原题链接
简单
作者:
Ccc1Z
,
2020-07-15 20:32:37
,
所有人可见
,
阅读 401
思路:
- DFS枚举每个最高点(根节点)的左子树加右子树的深度和
- ans = Math.max(ans,left+right)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int ans = 0;
public int diameterOfBinaryTree(TreeNode root) {
if(root == null)
return 0;
dfs(root);
return ans;
}
private int dfs(TreeNode root){
if(root == null)
return 0;
int left = dfs(root.left);
int right = dfs(root.right);
ans = Math.max(ans,left + right);
return Math.max(left,right)+1;
}
}