一、题目
563. 二叉树的坡度 - 力扣(LeetCode)
二、代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int Degree(TreeNode* root, int& Total )
{
if(root == nullptr)
{
return 0;
}
int leftDegree = Degree(root->left,Total);
int rightDegree = Degree(root->right,Total);
int x=abs(leftDegree-rightDegree);//当前结点的坡度
Total +=x;
return leftDegree+rightDegree+root->val;
}
int findTilt(TreeNode* root) {
int Total =0;
Degree(root,Total);
return Total;
}
};