Problem
https://leetcode.com/problems/binary-tree-tilt/description/
题目大意:返回树的总tilt值。对于一个节点的tilt值定义为左右子树元素和的绝对之差。
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.
Solution: Recursion
Time complexity: O(n)
Space complexity: O(h)
C++
v1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua // Running time: 17 ms class Solution { public: int findTilt(TreeNode* root) { int sum; return findTilt(root, sum); } private: // return the total tilt and sum of the root. int findTilt(TreeNode* root, int& sum) { if (root == nullptr) return 0; int ls = 0; int rs = 0; int tl = findTilt(root->left, ls); int tr = findTilt(root->right, rs); sum = root->val + ls + rs; return tl + tr + abs(ls - rs); } }; |
v1-2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Author: Huahua // Running time: 17 ms class Solution { public: int findTilt(TreeNode* root) { return findTiltSum(root).first; } private: pair<int, int> findTiltSum(TreeNode* root) { if (root == nullptr) return {0, 0}; auto l = findTiltSum(root->left); auto r = findTiltSum(root->right); return { l.first + r.first + abs(l.second - r.second), root->val + l.second + r.second }; } }; |
v2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua // Running time: 16 ms class Solution { public: int findTilt(TreeNode* root) { ans_ = 0; sum(root); return ans_; } private: int ans_; int sum(TreeNode* root) { if (root == nullptr) return 0; int l = sum(root->left); int r = sum(root->right); ans_ += abs(l - r); return root->val + l + r; } }; |
Python3
1 2 3 4 5 6 7 8 9 10 11 12 |
""" Author: Huahua Running time: 112 ms """ class Solution: def findTilt(self, root): def findTilt(root): if not root: return 0, 0 tl, sl = findTilt(root.left) tr, sr = findTilt(root.right) return tl + tr + abs(sl - sr), root.val + sl + sr return findTilt(root)[0] |