Skip to content

Commit 9d4b438

Browse files
committed
Add solution #563
1 parent 239a52b commit 9d4b438

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@
170170
542|[01 Matrix](./0542-01-matrix.js)|Medium|
171171
551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy|
172172
557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy|
173+
563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy|
173174
565|[Array Nesting](./0565-array-nesting.js)|Medium|
174175
566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy|
175176
567|[Permutation in String](./0567-permutation-in-string.js)|Medium|

solutions/0563-binary-tree-tilt.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 563. Binary Tree Tilt
3+
* https://leetcode.com/problems/binary-tree-tilt/
4+
* Difficulty: Easy
5+
*
6+
* Given the root of a binary tree, return the sum of every tree node's tilt.
7+
*
8+
* The tilt of a tree node is the absolute difference between the sum of all
9+
* left subtree node values and all right subtree node values. If a node does
10+
* not have a left child, then the sum of the left subtree node values is
11+
* treated as 0. The rule is similar if the node does not have a right child.
12+
*/
13+
14+
/**
15+
* Definition for a binary tree node.
16+
* function TreeNode(val, left, right) {
17+
* this.val = (val===undefined ? 0 : val)
18+
* this.left = (left===undefined ? null : left)
19+
* this.right = (right===undefined ? null : right)
20+
* }
21+
*/
22+
/**
23+
* @param {TreeNode} root
24+
* @return {number}
25+
*/
26+
var findTilt = function(root) {
27+
const result = { val: 0 };
28+
dfs(root, result);
29+
return result.val;
30+
};
31+
32+
function dfs(root, tilt) {
33+
if (!root) return 0;
34+
const left = dfs(root.left, tilt);
35+
const right = dfs(root.right, tilt);
36+
tilt.val += Math.abs(left - right);
37+
return root.val + left + right;
38+
}

0 commit comments

Comments
 (0)