Minimum Subtree

題目描述:

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

樣例:

Given a binary tree:

     1
   /   \
 -5     2
 / \   /  \
0   2 -4  -5 
return the node 1.

代碼實現(xiàn):

/**
 * 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;
 *     }
 * }
 */
class ResultType {
    TreeNode node;
    public int sum;
    public ResultType(int sum) {
        this.sum = sum;
    }
}
public class Solution {
    /**
     * @param root the root of binary tree
     * @return the root of the minimum subtree
     */
    private TreeNode subtree = null;
    private int subtreeSum = Integer.MAX_VALUE;
    public TreeNode findSubtree(TreeNode root) {
        helper(root);
        return subtree;
    }
    private ResultType helper(TreeNode root) {
        if (root == null) {
            return new ResultType(0);
        }
        ResultType left = helper(root.left);
        ResultType right = helper(root.right);
        ResultType result = new ResultType(left.sum + right.sum + root.val);
        //int sum = helper(root.left) + helper(root.right) + root.val;
        if (result.sum < subtreeSum) {
            subtreeSum = result.sum;
            subtree = root;
        }
        return result;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,891評論 0 33
  • 設(shè)置float的元素,會脫離文檔流,往設(shè)置的方向進行浮動,直到遇到父級的邊界或者其他的浮動元素 就會停止。 浮動的...
    沒_有_人閱讀 359評論 2 5
  • MySQL目前主要有以下幾種索引類型:FULLTEXT,HASH,BTREE,RTREE。 全索引哈希索引二叉樹索...
    4ea0af17fd67閱讀 240評論 0 0
  • 對于未來的預(yù)測,總是伴隨著恐懼。最近看《befyond feelings》和文章中的這些話感同身受:真正開始做功課...
    方知方行閱讀 253評論 0 1

友情鏈接更多精彩內(nèi)容