Skip to content

Commit 77c0df9

Browse files
solves binary tree tilt
1 parent a2233ea commit 77c0df9

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@
148148
| 557 | [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii) | Easy | [![Java](assets/java.png)](src/ReverseWordsInStringIII.java) [![Python](assets/python.png)](python/reverse_words_in_string_iii.py) |
149149
| 559 | [Maximum Depth of N-Ary Tree](https://leetcode.com/problems/maximum-depth-of-n-ary-tree) | Easy | [![Java](assets/java.png)](src/MaximumDepthOfNAryTree.java) [![Python](assets/python.png)](python/maximum_depth_of_n_ary_tree.py) |
150150
| 561 | [Array Partition I](https://leetcode.com/problems/array-partition-i) | Easy | [![Java](assets/java.png)](src/ArrayPartitionI.java) [![Python](assets/python.png)](python/array_partiton_I.py) |
151-
| 563 | [Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt) | Easy | |
151+
| 563 | [Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt) | Easy | [![Java](assets/java.png)](src/BinaryTreeTilt.java) [![Python](assets/python.png)](python/binary_tree_tilt.py) |
152152
| 566 | [Reshape The Matrix](https://leetcode.com/problems/reshape-the-matrix) | Easy | |
153153
| 572 | [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree) | Easy | |
154154
| 575 | [Distribute Candies](https://leetcode.com/problems/distribute-candies) | Easy | |

Diff for: python/binary_tree_tilt.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Definition for a binary tree node.
2+
class TreeNode:
3+
def __init__(self, val=0, left=None, right=None):
4+
self.val = val
5+
self.left = left
6+
self.right = right
7+
8+
9+
class Solution:
10+
def __init__(self):
11+
self.sumTilts = 0
12+
13+
def computeTilts(self, root: TreeNode) -> int:
14+
if root is None: return 0
15+
leftSum, rightSum = self.computeTilts(root.left), self.computeTilts(root.right)
16+
self.sumTilts += abs(leftSum - rightSum)
17+
return leftSum + rightSum + root.val
18+
19+
def findTilt(self, root: TreeNode) -> int:
20+
self.computeTilts(root)
21+
return self.sumTilts

Diff for: src/BinaryTreeTilt.java

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
public class BinaryTreeTilt {
2+
public int sumTilts = 0;
3+
4+
public int findTilt(TreeNode root) {
5+
computeTilt(root);
6+
return sumTilts;
7+
}
8+
9+
private int computeTilt(TreeNode root) {
10+
if (root == null) return 0;
11+
int leftSum = computeTilt(root.left);
12+
int rightSum = computeTilt(root.right);
13+
sumTilts += Math.abs(leftSum - rightSum);
14+
return leftSum + rightSum + root.val;
15+
}
16+
}

0 commit comments

Comments
 (0)