求二叉树的最大路径和
程序员文章站
2022-05-06 21:36:42
...
//二叉树节点的定义
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
//方法一:递归解法,时间复杂度过高
public int maxPathSum2(TreeNode root) {
if(root==null)
return 0;
int count=Math.max(maxPathSum(root.left),maxPathSum(root.right));
int tem=Math.max(count,count+root.val);
return Math.max(tem,maxPathSum(root.left)+maxPathSum(root.right)+root.val);
}
int maxValue;
public int maxPathSum(TreeNode root) {
maxValue=Integer.MIN_VALUE;
maxPath(root);
return maxValue;
}
//方法二:递归解法的优化
public int maxPath(TreeNode node) {
if(node==null)
return 0;
int left=Math.max(0,maxPath(node.left));
int right=Math.max(0,maxPath(node.right));
maxValue=Math.max(maxValue,left+right+node.val);
return Math.max(left,right)+node.val;
}
public static void main(String[]args){
// System.out.println("Hello");
TreeNode root=new TreeNode(-1);
root.left=new TreeNode(2);
root.right=new TreeNode(3);
root.left.left=new TreeNode(4);
Solution s=new Solution();
System.out.println(s.maxPathSum(root));
}
}
上一篇: 二叉树
下一篇: PHP实现返回JSON和XML的类分享