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

一个例子

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;
    }
};

简单的分治的思想就可以解决这个问题。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,186评论 0 10
  • 清明时节雨纷纷,路上行人欲断魂。借问酒家何处有?牧童遥指杏花村。—唐·杜牧 武侠江湖专题活动—琅琊令 武侠江湖专题...
    故乡圆月明阅读 4,322评论 26 23
  • 0、这是我看过漫威电影中,最贱的一部了。实在是贱的太可爱了。1、还是史上最黄暴最污的,还得说是最贱最搞笑的。2、要...
    扫地小沙弥阅读 4,361评论 0 1
  • 人,要顾虑到太多的东西。 生 老 病 死 总会有人问:明知道自己最后会消失,那为什么还要存在呢? 关于这个问题...
    YU婷阅读 1,040评论 0 0
  • 死亡从来都是一个很严肃的话题,因为恐惧,害怕失去或是对周遭的事物的依恋。 无论我们的生命还有三个月,三年,还是三十...
    风中的叶1212阅读 2,953评论 0 0

友情链接更多精彩内容