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 <stdio.h>
2#include <stdlib.h>
3#include <math.h>
4
5struct TreeNode {
6 int val;
7 struct TreeNode *left;
8 struct TreeNode *right;
9};
10
11int findTiltUtil(struct TreeNode* root, int* tiltSum) {
12 if (root == NULL) return 0;
13
14 int leftSum = findTiltUtil(root->left, tiltSum);
15 int rightSum = findTiltUtil(root->right, tiltSum);
16
17 *tiltSum += abs(leftSum - rightSum);
18
19 return root->val + leftSum + rightSum;
20}
21
22int findTilt(struct TreeNode* root) {
23 int tiltSum = 0;
24 findTiltUtil(root, &tiltSum);
25 return tiltSum;
26}
The C solution uses a helper function findTiltUtil
which computes the sum of subtree node values and the tilt. It takes a pointer to tiltSum
which accumulates the total tilt as a side effect.
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.