-
SLPHPython:
class Solution(object): def findTilt(self, root): """ :type root: TreeNode :rtype: int """ self.ans = 0 def subTreeSum(root): if not root: return 0 lsum = subTreeSum(root.left) rsum = subTreeSum(root.right) self.ans += abs(lsum - rsum) return root.val + lsum + rsum subTreeSum(root) return self.ans
-
SLPHJava:
public class Solution { private int sum = 0; public int findTilt(TreeNode root) { helper(root); return sum; } private int helper(TreeNode root) { if (root == null) return 0; int left = helper(root.left); int right = helper(root.right); sum += Math.abs(left - right); return root.val + left + right; } }
-
SLPHC++解法一:
class Solution { public: unordered_map<TreeNode*, int> m; int findTilt(TreeNode* root) { if (!root) return 0; int tilt = abs(getSum(root->left, m) - getSum(root->right, m)); return tilt + findTilt(root->left) + findTilt(root->right); } int getSum(TreeNode* node, unordered_map<TreeNode*, int>& m) { if (!node) return 0; if (m.count(node)) return m[node]; return m[node] = getSum(node->left, m) + getSum(node->right, m) + node->val; } };
-
SLPHC++解法二:
class Solution { public: int findTilt(TreeNode* root) { int res = 0; postorder(root, res); return res; } int postorder(TreeNode* node, int& res) { if (!node) return 0; int leftSum = postorder(node->left, res); int rightSum = postorder(node->right, res); res += abs(leftSum - rightSum); return leftSum + rightSum + node->val; } };
-