1. Description
Given the root of a binary tree, return the sum of every tree node's tilt.
The tilt of a tree node is the absolute difference between sum of all left subtree values and all right subtree node values. If a node does not have a left child then the sum of the left subtree node values is treated as 0. The rule is similar if the node doe not have a right child.
constraints :
- The number of nodes in the tree is in the range [0, \(10^{4}\)].
- -1000 <= Node.val <= 1000
2. Algorithms
Let's see when we got [4, 2, 9, 3, 5, null, 7] as input. Then our result of algorithm will be : | 0 - 0 | + | 0 - 0 | + | 0 - 0 | + | 3 - 5 | + | 0 - 7 | + | ( 3 + 5 + 2 ) - ( 9 + 7 ) | = 0 + 0 + 0 + 2 + 7 + 6 = 15.
- Start
- Declare variable named sum_.
- Initilalize sum_ to 0.
- Declare function named helper which get root as input.
- Set num_ as nonlocal.
- (Base case) If root is None, return 0.
- Traverse left subtree recursively.
- Traverse right subtree recursively.
- Add up absolute difference between left value and right value.
- Return sum between left and right and value which sum of all left subtree values and all right subtree node values recursively.
- End
3. Codes
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findTilt(self, root: Optional[TreeNode]) -> int:
sum_ = 0
def helper(root) :
nonlocal sum_
if root is None :
return 0
left = helper(root.left)
right = helper(root.right)
sum_ += abs(left - right)
return left + right + root.val
helper(root)
return sum_
4. Conclusion
'LeetCode > Easy' 카테고리의 다른 글
572 Subtree of Another Tree (0) | 2022.09.06 |
---|---|
566 Reshape Matrix (0) | 2022.09.06 |
561 Array Partition (0) | 2022.09.06 |
559 Maximum Depth of N-ary Tree (0) | 2022.09.06 |
557 Reverse Words in a String III (0) | 2022.09.05 |