1、二叉树中的最大路径和
给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
示例 1:
输入: [1,2,3] 1 / \ 2 3 输出: 6
示例 2:
输入: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7 输出: 42
class Solution(object): def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ temp,res=self.helper(root) return res #计算最长路径和 def path(self,root,maxres,sumval): if root: sumval+=root.val maxres=max(maxres,sumval) left=right=maxres if root.left: left=self.path(root.left,maxres,sumval) if root.right: right=self.path(root.right,maxres,sumval) return max(left,right) return 0 #(root,左路+root,右路+root,左最大值,右最大值)比较得到最大值 def helper(self,root): if not root: return -10000,-10000 maxres=root.val sumval=0 lpath,lre=self.helper(root.left) rpath,rre=self.helper(root.right) return self.path(root,maxres,sumval),max(lre,rre,lpath+rpath+root.val,root.val,lpath+root.val,rpath+root.val)
2、路径求和(两个递归求解)
给定一个二叉树,它的每个结点都存放着一个整数值。
找出路径和等于给定数值的路径总数。
路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
示例:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 返回 3。和等于 8 的路径有: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11
class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: int """ self.res=0 def ans(root,cur,sum): cur+=root.val if cur==sum: self.res+=1 if root.left: ans(root.left,cur,sum) if root.right: ans(root.right,cur,sum) def helper(root,sum): if root: ans(root,0,sum) if root.left: helper(root.left,sum) if root.right: helper(root.right,sum) helper(root,sum) return self.res