Я думаю, что вас смущает то, что вычисление суммы левого и правого поддерева и вычисление наклона для каждого узла объединено в одном методе.Итак, я упростил код, который вы предоставили, чтобы его было легче понять, и добавил к нему комментарии.Хотя этот способ гораздо менее эффективен, потому что вы вычисляете сумму для левого и правого поддерева каждого узла (при каждом вызове calculateTilt
), но он все еще принимается с помощью кода leetcode:
public class Solution {
int result = 0; //instance variable to accumulate result(tilt) for all nodes in the tree
public int findTilt(TreeNode root) {
calculateTilt(root);
return result;
}
private void calculateTilt(TreeNode root) {
if (root == null)
return;
int left = findTreeSum(root.left); //find sum of all nodes values of the left subtree
int right = findTreeSum(root.right); //find sum of all nodes values of the right subtree
result += Math.abs(left - right); //add tilt of current node to the result
calculateTilt(root.left); //recursively calculate tilt for the left subtree
calculateTilt(root.right); //recursively calculate tilt for the right subtree
}
//method to find sum of all nodes values for the tree starting at root
private int findTreeSum(TreeNode root){
if (root == null)
return 0;
return findTreeSum(root.left) + findTreeSum(root.right) + root.val;
}
}
Надеюсь, что этопоможет!