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;
        }
    }
  • 相关阅读:
    PERL 学习
    javascript
    Netfilter
    PHP内核探索
    Linux内存管理学习笔记 转
    使用mysqladmin ext 了解MySQL运行状态 转
    在ArcGIS Desktop中进行三参数或七参数精确投影转换
    AE 栅格图分级渲染
    ArcEngine标注和注记
    ArcGIS Engine 线段绘制
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12416243.html
Copyright © 2011-2022 走看看