题目连接ide
题目大意:找出一个二叉树中的最大路径长度。这个路径是从一个叶子结点到另外一个叶子结点的路径长度。例子以下:spa
法一:DFS。因为是左边一个路径到右边一个路径,通过中间的根链接点,所获得的路径和,因此能够计算每一个根节点的左子树和右子树的最大路径和,而后再从中选大者,再与其上一层进行比较。具体代码以下(耗时2ms):code
1 //设为全局,方便计算,由于最大值有多是中间路径,因此若是只是做为参数返回的话,很差承接 2 int res = Integer.MIN_VALUE; 3 public int maxPathSum(TreeNode root) { 4 dfs(root); 5 return res; 6 } 7 private int dfs(TreeNode root) { 8 if(root == null) { 9 return 0; 10 } 11 //计算左子树最大路径和 12 int left = Math.max(dfs(root.left), 0); 13 //计算右子树最大路径和 14 int right = Math.max(dfs(root.right), 0); 15 //求max 16 res = Math.max(res, left + right + root.val); 17 //取左子树和右子树的较大值,再加上当前根值返回给上一级 18 return Math.max(left, right) + root.val; 19 }