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;
        }
    }
  • 相关阅读:
    SQL server使用
    NCC 事务
    springboot学习
    容器
    x86汇编
    git之.gitignore文件用途
    Linux系统安装之U盘引导
    使用异步I/O大大提高应用程序的性能
    Python3.5 用 pip 安装lxml时出现 “Unable to find vcvarsall.bat ”?(转载)
    python之正则表达式
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12416243.html
Copyright © 2011-2022 走看看