0%

binary-tree-tilt

Binary Tree Tilt – LeetCode 563

Problem

Description

Given a binary tree, return the tilt of the whole tree.

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.

The tilt of the whole tree is defined as the sum of all nodes’ tilt.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
unsigned tilt = 0;
int recursive(TreeNode* root){
if(root){
int left = recursive(root->left);
int right = recursive(root->right);
tilt += abs(left - right);
return left + right + root->val;
} else
return 0;
}
public:
int findTilt(TreeNode* root) {
recursive(root);
return tilt;
}
};

思路

正常DFS。时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$8$ ms,排名$2.31\%$

Better

思路

还没看到更好的思路。