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

在这里插入图片描述

Note

  • The sum of node values in any subtree won’t exceed the range of 32-bit integer.
  • All the tilt values won’t exceed the range of 32-bit integer.

Solution1

完全按照定义来。
增加辅助函数treeSum来求树的所有节点之和。

在findTilt中,先计算左子树的tilt,再计算右子树的tilt,最后计算根节点的tilt,三者之和就是整棵树的tilt。

/**
 * 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 findTilt(TreeNode* root) {
        if(!root)
            return 0;
        int leftTilt = findTilt(root->left);
        int rightTilt = findTilt(root->right);
        int rootTilt = abs(treeSum(root->left) - treeSum(root->right));

        return leftTilt+rootTilt + rightTilt;
        
    }
    int treeSum(TreeNode* root)
    {
        if(!root)
            return 0;
        return root->val + treeSum(root->left) + treeSum(root->right);
    }
};

Solution2

事实上,在求以一个节点为根的树的节点和时,就可以求出该根节点的tilt。

/**
 * 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 findTilt(TreeNode* root) {
        if(!root)
            return 0;
        int tilt = 0;
        treeSum(root,tilt);
        return tilt;
        
    }
    int treeSum(TreeNode* root,int& tilt)
    {
        if(!root)
            return 0;
        int leftSum = treeSum(root->left,tilt);
        int rightSum = treeSum(root->right,tilt);
        tilt += abs(leftSum - rightSum);
        return root->val + leftSum + rightSum;
    }
};
发布了427 篇原创文章 · 获赞 212 · 访问量 51万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览