解法一
先得到左右两个子节点的总和,再分情况递归
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public int findTilt(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 0;
} else if (root.left != null && root.right == null) {
return Math.abs(getLeftValue(root)) + findTilt(root.left);
} else if (root.left == null && root.right != null) {
return Math.abs(getRightValue(root)) + findTilt(root.right);
} else {
return Math.abs(getLeftValue(root) - getRightValue(root)) + findTilt(root.left) + findTilt(root.right);
}
}
public int getLeftValue(TreeNode treeNode) {
if (treeNode.left == null) {
return 0;
}
return getLeftValue(treeNode.left) + getRightValue(treeNode.left) + treeNode.left.val;
}
public int getRightValue(TreeNode treeNode) {
if (treeNode.right == null) {
return 0;
}
return getLeftValue(treeNode.right) + getRightValue(treeNode.right) + treeNode.right.val;
}
}
解法二
直接对某个节点向下递归
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
int ans = 0;
public int findTilt(TreeNode root) {
dfs(root);
return ans;
}
public int dfs(TreeNode node) {
if (node == null) {
return 0;
}
int sumLeft = dfs(node.left);
int sumRight = dfs(node.right);
ans += Math.abs(sumLeft - sumRight);
return sumLeft + sumRight + node.val;
}
}