Leetcode 563 Binary Tree Tilt
题目原文
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:
Input:
1
/ \
2 3
Output: 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1
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.
题意分析
对于一个二叉树(不一定满),每一个点都有一个tilt值,其值为左子树node的value之和与右子树node的value之差的绝对值。求二叉树每个node的tilt之和。
解法分析
本题采用递归思想,函数每一次返回一个pair,first代表子树的tilt,second代表子树node之和,C++代码如下:
/**
* 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:
pair<int,int> tilt_and_sum(TreeNode* a){
pair<int,int> res;
if(a==NULL){
res.first=0;
res.second=0;
return res;
}
pair<int,int> left=tilt_and_sum((*a).left);
pair<int,int> right=tilt_and_sum((*a).right);
res.first=left.first+right.first+abs(left.second-right.second);
res.second=left.second+right.second+(*a).val;
return res;
}
int findTilt(TreeNode* root) {
pair<int,int> res;
res=tilt_and_sum(root);
return res.first;
}
};