亚麻:max sbustree

这是亚麻的OA 题

这里的代码没有经过测试

Given a binary tree, find the subtree with maximum sum. Return the root of the subtree.

 

another similar problem in leetcode :

https://leetcode.com/problems/most-frequent-subtree-sum/description/

which has passed all the testcases.


// key point
// use recursive
// use maxval and node to record the point meet the requirement . can also use pair( maxval , node ) to recorde the max value point.

struct
TreeNode { TreeNode* right = null; TreeNode* left =null ; int val =0; } int _MaxSubtree ( TreeNode* root , TreeNode* & res , int maxvalue){ if ( root == null ) return 0; int vall = _MaxSubtree( root.left , res, maxvalue); int valr =_MaxSubtree (root.right, res. maxvalue); int val = root.val + vall + valr; if ( val > res ){ res = root; maxvalue = val; } return val; } } TreeNode * MaxSubtree ( TreeNode* root ){ if (root == null ) return null; TreeNode* res == null; int maxval = INT_MIN; _ MaxSubtree( root, res, maxval); return res; }

 

posted @ 2018-01-16 13:42  HisonSanDiego  阅读(128)  评论(0编辑  收藏  举报