这是亚麻的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.
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; }