1. 题目
2. 思路
(1) 递归
- 利用全局变量记录坡度之和,利用递归函数返回当前结点的坡度即可。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
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 {
private int res;
public int findTilt(TreeNode root) {
recur(root);
return res;
}
private int recur(TreeNode root) {
if (root == null) {
return 0;
}
int left = recur(root.left);
int right = recur(root.right);
res += Math.abs(left - right);
return left + right + root.val;
}
}