脑回路清奇,不用成员变量的怪异方法
二叉树的最大路径和
http://www.nowcoder.com/questionTerminal/da785ea0f64b442488c125b441a4ba4a
函数参数m表示不包含本节点或者同时包含左右子节点的最大值,mc表示包含本节点的最大值,这样遍历至某个节点的最大值等于,左子树的m/mc值,或者右子树的m/mc值,或者max(0,左子树mc值) + max(0,右子树mc值) + 本节点值,取这几个中最大的
代码如下:
#define INF 1e9 class Solution { public: void dfs(TreeNode* root, int& m, int& mc){ if(!root) return ; mc=root->val; m=-INF; int l,lc; l=lc=-INF; int r,rc; r=rc=-INF; if(root->left){ dfs(root->left,l,lc); } if(root->right){ dfs(root->right,r,rc); } if(l>-INF){ if(r>-INF){ m = max(max(max(l,r),lc+rc+mc), max(lc,rc)); mc = mc + max(0,max(lc,rc)); }else{ if(rc>-INF){ m = max(max(l,lc+rc+mc),max(rc,lc)); mc = mc + max(0,max(lc,rc)); }else{ m = max(l, lc); mc = mc + max(0, lc); } } }else{ if(lc>-INF){ if(r>-INF){ m = max(max(r, lc+rc+mc), max(lc,rc)); mc = mc + max(0, max(lc,rc)); }else{ if(rc>-INF){ m = max(lc + rc + mc, max(lc,rc)); mc = mc + max(0, max(lc,rc)); }else{ m = lc; mc = mc + max(0,lc); } } }else{ if(r>-INF){ m = max(r,rc); mc = mc + max(0, rc); }else{ if(rc>-INF){ m = rc; mc = mc + max(0, rc); } } } } } int maxPathSum(TreeNode* root) { // write code here int m, mc; m=0; mc=root->val; dfs(root,m,mc); return max(m,mc); } };