Leetcode筆記——563. Binary Tree Tilt

Problem

Given a binary tree, return the tilt of the whole tree.

The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.

The tilt of the whole tree is defined as the sum of all nodes' tilt.

Example

一個(gè)例子

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int tilt = 0;
    int findTilt(TreeNode* root) {
        traverse(root);
        return tilt;
    }
    
    int traverse(TreeNode* root)
    {
        if (root == NULL) return 0;
        int left = traverse(root->left);
        int right = traverse(root->right);
        tilt += abs(left-right);
        return left+right+root->val;
    }
};

簡單的分治的思想就可以解決這個(gè)問題。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,854評(píng)論 0 10
  • 清明時(shí)節(jié)雨紛紛,路上行人欲斷魂。借問酒家何處有?牧童遙指杏花村。—唐·杜牧 武俠江湖專題活動(dòng)—瑯琊令 武俠江湖專題...
    故鄉(xiāng)圓月明閱讀 902評(píng)論 26 23
  • 0、這是我看過漫威電影中,最賤的一部了。實(shí)在是賤的太可愛了。1、還是史上最黃暴最污的,還得說是最賤最搞笑的。2、要...
    掃地小沙彌閱讀 962評(píng)論 0 1
  • 人,要顧慮到太多的東西。 生 老 病 死 總會(huì)有人問:明知道自己最后會(huì)消失,那為什么還要存在呢? 關(guān)于這個(gè)問題...
    YU婷閱讀 112評(píng)論 0 0
  • 死亡從來都是一個(gè)很嚴(yán)肅的話題,因?yàn)榭謶?,害怕失去或是?duì)周遭的事物的依戀。 無論我們的生命還有三個(gè)月,三年,還是三十...
    風(fēng)中的葉1212閱讀 419評(píng)論 0 0

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