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.
1class TreeNode {
2 int val;
3 TreeNode left;
4 TreeNode right;
5 TreeNode(int x) { val = x; }
6}
7
8class Solution {
9 private int tiltSum = 0;
10
11 public int findTilt(TreeNode root) {
12 sumAndTilt(root);
13 return tiltSum;
14 }
15
16 private int sumAndTilt(TreeNode node) {
17 if (node == null) return 0;
18
19 int left = sumAndTilt(node.left);
20 int right = sumAndTilt(node.right);
21 tiltSum += Math.abs(left - right);
22 return node.val + left + right;
23 }
24}
In the Java solution, a class-level variable tiltSum
is used to store the total tilt. The sumAndTilt
method calculates the subtree sums and tilt for a node.
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.