整体思路:其实就是对于树的每一个结点的左右子树相加,看看哪个结点的直径最大而已。
有人会认为只有经过根的那条路径才是最长的直径,其实不然,我们需要考虑更周到一点才行,只有遍历全部结点才能确定。
实现一:用递归实现
用两个函数,一个函数用来获取当前结点的深度,一个函数用来遍历树的结点。这里的遍历方式采用了前序遍历。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int maxs=0;
public int diameterOfBinaryTree(TreeNode root) {
if(root==null)
return 0;
qianxu(root);
return maxs;
}
public int getHeight(TreeNode t,int cnt){
if(t==null)
return cnt;
cnt++;
return Math.max(getHeight(t.right,cnt),getHeight(t.left,cnt));
}
public void qianxu(TreeNode t){
if(t==null)
return;
int res=getHeight(t.left,0)+getHeight(t.right,0);
maxs=Math.max(res,maxs);
qianxu(t.left);
qianxu(t.right);
}
}
实现二:DFS
这种方法其实就是把递归中的两个函数合在一起使用了,这样大大降低了时间复杂度。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int maxs=0;
public int diameterOfBinaryTree(TreeNode root) {
if(root==null)
return 0;
dfs(root);
return maxs;
}
public int dfs(TreeNode t){
if(t==null)
return 0;
int l=dfs(t.left);
int r=dfs(t.right);
maxs=Math.max(maxs,l+r);
return Math.max(l,r)+1;
}
}