Leetcode 563. Binary Tree Tilt
这题考察找树的坡度,我们直接返回左节点减右节点的绝对值加左节点的坡度加右节点的坡度。 getSum是找节点和,调用左节点的和加右节点的和加上本节点的值
/** * 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; return abs(getSum(root->left, 0) - getSum(root->right, 0)) + findTilt(root->left) + findTilt(root->right); } int getSum(TreeNode* root, int sum) { if(!root) return 0; return getSum(root->left, sum) + getSum(root->right, sum) + root->val; } };