版权声明:请注明转载地址 https://blog.csdn.net/OCEANtroye https://blog.csdn.net/OCEANtroye/article/details/83592606
[LeetCode][563] Binary Tree Tilt题解
给定一个树,定义一个树的左右子树的差值的绝对值为树的坡度。
要求返回树的所有节点的坡度的和
dfs搜索左右子树的和 然后相减取绝对值,将这个结果累加到全局变量res上
dfs作用即是记录当前树的总和,以便它的父亲调用(回溯时候调用)
/*
* [563] Binary Tree Tilt
*
* https://leetcode.com/problems/binary-tree-tilt/description/
*
* algorithms
* Easy (46.46%)
* Total Accepted: 39.4K
* Total Submissions: 84.9K
* Testcase Example: '[1,2,3]'
*
* 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.
*
*
*/
/**
* 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
{
private:
int res;
public:
int findTilt(TreeNode *root)
{
res = 0;
dfs(root);
return res;
}
//返回的当前节点的左右子树和自己节点的和
//因此
//每一次dfs 用temp记录当前的累加值
//而使用dfs的返回值(当前树的总共的值)作为返回给父亲节点来调用
int dfs(TreeNode *root)
{
if (root == nullptr)
{
return 0;
}
//如果是叶子节点
int l=dfs(root->left);
int r=dfs(root->right);
res+=abs(l-r);
return l+r+root->val;
}
};
参考https://leetcode.com/problems/binary-tree-tilt/discuss/102323/C+±easy-and-clean-soluion