Skip to content

Commit 30a4ed7

Browse files
authored
Create 563._Binary_Tree_Tilt.md
1 parent 7749c31 commit 30a4ed7

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# 563. Binary Tree Tilt
2+
3+
**<font color=red>难度: Easy</font>**
4+
5+
## 刷题内容
6+
7+
> 原题连接
8+
9+
* https://leetcode.com/problems/binary-tree-tilt/description/
10+
11+
> 内容描述
12+
13+
```
14+
15+
Given a binary tree, return the tilt of the whole tree.
16+
17+
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.
18+
19+
The tilt of the whole tree is defined as the sum of all nodes' tilt.
20+
21+
Example:
22+
Input:
23+
1
24+
/ \
25+
2 3
26+
Output: 1
27+
Explanation:
28+
Tilt of node 2 : 0
29+
Tilt of node 3 : 0
30+
Tilt of node 1 : |2-3| = 1
31+
Tilt of binary tree : 0 + 0 + 1 = 1
32+
Note:
33+
34+
The sum of node values in any subtree won't exceed the range of 32-bit integer.
35+
All the tilt values won't exceed the range of 32-bit integer.
36+
```
37+
38+
## 解题方案
39+
40+
> 思路 1
41+
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******
42+
43+
44+
45+
写一个sums函数,input为node,返回这个node本身的value和它所有孩子的value之和,该node的tilt就是左孩子sums和右孩子sums的差值的绝对值
46+
47+
然后对于root和其所有子孙,只需要把他们的tilt全部加起来就是结果
48+
49+
```python
50+
class Solution(object):
51+
def findTilt(self, root):
52+
"""
53+
:type root: TreeNode
54+
:rtype: int
55+
"""
56+
self.res = 0
57+
def sums(node):
58+
if not node:
59+
return 0
60+
left_sum = sums(node.left)
61+
right_sum = sums(node.right)
62+
self.res += abs(left_sum-right_sum)
63+
return left_sum + right_sum + node.val
64+
65+
sums(root)
66+
return self.res
67+
```
68+
69+
70+
71+
72+
73+
74+
75+
76+
77+
78+
79+
80+
81+
82+
83+

0 commit comments

Comments
 (0)