The idea behind the post-order traversal approach is to calculate the tilt of a node when all its children have been processed. For each node, compute the sum of node values for the left and right subtrees separately, calculate the node's tilt as the absolute difference of these two sums, and then propagate these subtree sums up to the parent node.
Time Complexity: O(n) where n is the number of nodes, as we visit each node once. Space Complexity: O(h) where h is the height of the tree, due to the recursion stack.
1#include <cmath>
2using namespace std;
3
4struct TreeNode {
5 int val;
6 TreeNode *left;
7 TreeNode *right;
8 TreeNode(int x) : val(x), left(NULL), right(NULL) {}
9};
10
11class Solution {
12public:
13 int findTilt(TreeNode* root) {
14 int tiltSum = 0;
15 sumAndTilt(root, tiltSum);
16 return tiltSum;
17 }
18
19 int sumAndTilt(TreeNode* node, int& tiltSum) {
20 if (node == nullptr) return 0;
21
22 int left = sumAndTilt(node->left, tiltSum);
23 int right = sumAndTilt(node->right, tiltSum);
24 tiltSum += abs(left - right);
25 return node->val + left + right;
26 }
27};
The C++ solution defines a helper method sumAndTilt
within a class Solution
. This helper recursively computes the sum of each subtree and updates the total tilt in the reference variable tiltSum
.
In this approach, we preprocess the subtree sums for each node iteratively or recursively. Then we use these sums to calculate the tilt for each node in a separate pass through the tree. This separation of concerns can offer cleaner logic and easier maintenance of code.
Time Complexity: O(n^2) because calculateSubtreeSum might be called multiple times. Space Complexity: O(h).
1public class TreeNode {
2 public int val;
3 public TreeNode left;
4 public TreeNode right;
5 public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
6 this.val = val;
7 this.left = left;
8 this.right = right;
9 }
10}
11
12public class Solution {
13
14 private int CalculateSubtreeSum(TreeNode node) {
15 if (node == null) return 0;
16 return node.val + CalculateSubtreeSum(node.left) + CalculateSubtreeSum(node.right);
17 }
18
19 private int CalculateTilt(TreeNode node) {
20 if (node == null) return 0;
21 int leftSum = CalculateSubtreeSum(node.left);
22 int rightSum = CalculateSubtreeSum(node.right);
23 int leftTilt = CalculateTilt(node.left);
24 int rightTilt = CalculateTilt(node.right);
25 return Math.Abs(leftSum - rightSum) + leftTilt + rightTilt;
26 }
27
28 public int FindTilt(TreeNode root) {
29 return CalculateTilt(root);
30 }
31}
In C#, the logical separation of subtree sum and tilt computation into distinct methods introduces clarity into recursive tree operations while emphasizing the tilt calculation as a distinct pass.