Skip to content

Commit fa4c36a

Browse files
authored
Create Binary Tree Tilt.py
1 parent 39e2820 commit fa4c36a

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Binary Tree Tilt.py

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
'''
2+
Given a binary tree, return the tilt of the whole tree.
3+
4+
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.
5+
6+
The tilt of the whole tree is defined as the sum of all nodes' tilt.
7+
8+
Example:
9+
Input:
10+
1
11+
/ \
12+
2 3
13+
Output: 1
14+
Explanation:
15+
Tilt of node 2 : 0
16+
Tilt of node 3 : 0
17+
Tilt of node 1 : |2-3| = 1
18+
Tilt of binary tree : 0 + 0 + 1 = 1
19+
Note:
20+
21+
The sum of node values in any subtree won't exceed the range of 32-bit integer.
22+
All the tilt values won't exceed the range of 32-bit integer.
23+
'''
24+
25+
26+
# Definition for a binary tree node.
27+
# class TreeNode(object):
28+
# def __init__(self, x):
29+
# self.val = x
30+
# self.left = None
31+
# self.right = None
32+
33+
class Solution(object):
34+
def findTilt(self, root):
35+
"""
36+
:type root: TreeNode
37+
:rtype: int
38+
"""
39+
x, y = self.postOrder(root, 0)
40+
return y
41+
42+
def postOrder(self, root, tilt):
43+
if not root:
44+
return 0, tilt
45+
46+
left, tilt = self.postOrder(root.left, tilt)
47+
right, tilt = self.postOrder(root.right, tilt)
48+
tilt += abs(left - right)
49+
50+
return left + right + root.val, tilt

0 commit comments

Comments
 (0)