美文网首页
Maximum Subtree

Maximum Subtree

作者: Wenyue_offer | 来源:发表于2017-09-14 01:56 被阅读0次

    public class Solution {
    /*
    * @param root: the root of binary tree
    * @return: the maximum weight node
    */
    public TreeNode result = null;
    public int maximum_weight = Integer.MIN_VALUE;

    public TreeNode findSubtree(TreeNode root) {
        // Write your code here
        helper(root);
        
        return result;
    }
    
    public int helper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left_weight = helper(root.left);
        int right_weight = helper(root.right);
    
        if (result == null || left_weight + right_weight + root.val > maximum_weight) {
            maximum_weight = left_weight + right_weight + root.val;
            result = root;
        }
    
        return left_weight + right_weight + root.val;
    }
    

    }

    相关文章

      网友评论

          本文标题: Maximum Subtree

          本文链接:https://www.haomeiwen.com/subject/ftjrsxtx.html