java数据结构与算法刷题目录(剑指Offer、LeetCode、ACM)-----主目录-----持续更新(进不去说明我没写完):https://blog.youkuaiyun.com/grd_java/article/details/123063846 |
---|
文章目录
解题思路 |
---|
- 采用深度优先遍历,从最底下的结点开始,计算每个结点的左子树和右子树高度
- 此时有两种选择
- 以当前结点为中心,连通左子树和右子树,获取路径长度
- 继续向上走,选择左右子树路径长的一条,加上自己,作为父结点的一棵子树,继续遍历
- 以上两种选择,我们都做,并且每次都保存最大值max
代码 |
---|
/**
* 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 max = Integer.MIN_VALUE;//保存最长路径
public int diameterOfBinaryTree(TreeNode root) {
dfs(root);//深度优先
return max;
}
public int dfs(TreeNode root) {
if(root == null) return 0;
int leftPath = dfs(root.left);//获取左子树路径长度
int rightPath = dfs(root.right);//获取右子树路径长度
//通过当前root连通左子树和右子树的路径长度为leftPath+rightPath
max = Math.max(max,leftPath+rightPath);//如果连通后更长就更新max
//然后继续遍历,放弃以当前结点连通左右子树
return Math.max(leftPath,rightPath)+1;//返回当前结点更长的路径长度
}
}