Description
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
1.The sum of node values in any subtree won't exceed the range of 32-bit integer.
2.All the tilt values won't exceed the range of 32-bit integer.
Solution 1(C++)
static int x=[](){std::ios::sync_with_stdio(false); cin.tie(NULL); return 0;}();
class Solution {
public:
int subTreeSum(TreeNode* node){
if(!node) return 0;
return node->val+subTreeSum(node->left)+subTreeSum(node->right);
}
int findTilt(TreeNode* root) {
if(!root) return 0;
return abs(subTreeSum(root->right)-subTreeSum(root->left))+findTilt(root->left)+findTilt(root->right);
}
};
Solution 2(C++)
class Solution {
public:
int findTilt(TreeNode* root) {
int totalTilt = 0, sum = 0;
sumTree(root, totalTilt);
return totalTilt;
}
int sumTree(TreeNode* root, int& totalTilt) {
if (root) {
int ls = sumTree(root->left, totalTilt);
int rs = sumTree(root->right, totalTilt);
totalTilt += abs(ls - rs);
return ls + rs + root->val;
}
return 0;
}
}
Solution 3(C++)
int x = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return 0;
}();
class Solution {
struct Result {
int sum;
int tilt;
};
Result traverse(TreeNode* root) {
if (!root) return {0, 0};
auto l = traverse(root->left);
auto r = traverse(root->right);
int tilt = std::abs(l.sum - r.sum) + l.tilt + r.tilt;
int sum = l.sum + r.sum + root->val;
return {sum, tilt};
}
public:
int findTilt(TreeNode* root) {
auto result = traverse(root);
return result.tilt;
}
};
算法分析
解法一是自己写的,,形式比较简单,但是好像算法比较复杂。其实是有部分重复,比如计算左右子树的节点和,可直接计算题目要求的那个值。
程序分析
感觉树的习题能很好锻炼递归,深度优先,广度优先等等。需要回头多做一做。