Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Dec 19, 2023. It is now read-only.

Commit aeb6522

Browse files
committed
Add problem 563
1 parent c4b7811 commit aeb6522

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

‎algorithms/563/README.md‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
## 563. Binary Tree Tilt
2+
3+
Given a binary tree, return the tilt of the **whole tree.**
4+
5+
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.
6+
7+
The tilt of the **whole tree** is defined as the sum of all nodes' tilt.
8+
9+
**Example:**
10+
<pre>
11+
<b>Input:</b>
12+
1
13+
/ \
14+
2 3
15+
<b>Output:</b> 1
16+
<b>Explanation:</b>
17+
Tilt of node 2 : 0
18+
Tilt of node 3 : 0
19+
Tilt of node 1 : |2-3| = 1
20+
Tilt of binary tree : 0 + 0 + 1 = 1
21+
</pre>
22+
23+
**Note:**
24+
25+
1. The sum of node values in any subtree won't exceed the range of 32-bit integer.
26+
2. All the tilt values won't exceed the range of 32-bit integer.

‎algorithms/563/solution.go‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package main
2+
3+
/**
4+
* Definition for a binary tree node.
5+
* type TreeNode struct {
6+
* Val int
7+
* Left *TreeNode
8+
* Right *TreeNode
9+
* }
10+
*/
11+
12+
// Time complexity, O(n) where n is size of the tree
13+
// Space complexity, O(1)
14+
func findTilt(root *TreeNode) int {
15+
var tilt int
16+
calcTilt(root, &tilt)
17+
return tilt
18+
19+
}
20+
21+
// Returns sum of the nodes and updates the tilt
22+
func calcTilt(root *TreeNode, tilt *int) int {
23+
if root == nil {
24+
return 0
25+
}
26+
l := calcTilt(root.Left, tilt)
27+
r := calcTilt(root.Right, tilt)
28+
t := l - r
29+
if t < 0 {
30+
t *= -1
31+
}
32+
*tilt += t
33+
return l + root.Val + r
34+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /