zoukankan      html  css  js  c++  java
  • [LintCode] 596. Minimum Subtree

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

    Example

    Example 1:

    Input:
    {1,-5,2,1,2,-4,-5}
    Output:1
    Explanation:
    The tree is look like this:
         1
       /   
     -5     2
     /    /  
    1   2 -4  -5 
    The sum of whole tree is minimum, so return the root.
    

    Example 2:

    Input:
    {1}
    Output:1
    Explanation:
    The tree is look like this:
       1
    There is one and only one subtree in the tree. So we return 1.

    /**
     * Definition of TreeNode:
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left, right;
     *     public TreeNode(int val) {
     *         this.val = val;
     *         this.left = this.right = null;
     *     }
     * }
     */
    
    public class Solution {
        /**
         * @param root: the root of binary tree
         * @return: the root of the minimum subtree
         */
        private TreeNode res = null;
        private int globalMin = Integer.MAX_VALUE;
        public TreeNode findSubtree(TreeNode root) {
            // write your code here
            helper(root);
            return res;
        }
        
        private int helper(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int left = helper(root.left);
            int right = helper(root.right);
            if (left + right + root.val < globalMin) {
                globalMin = left + right + root.val;
                res = root;
            }
            return left + right + root.val;
        }
    }
  • 相关阅读:
    Action常见注解的运用
    发现越来越喜欢来博客园了,所以自己也注册了一个!
    jsf 繁体教程下载pdf
    poj3210
    poj3224
    poj3219
    poj3233
    poj3372
    Paper Pal:一个中英文论文及其代码大数据搜索平台
    年轻就该多尝试,教你20小时Get一项新技能
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12416243.html
Copyright © 2011-2022 走看看