563. 二叉树的坡度
前言
后续遍历,递归。盗图一张过程
题目
源码
/**
* Definition for a binary tree node.
* public 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) {
helper(root);
return ans;
}
public int helper(TreeNode node){
if(node==null){
return 0;
}
int left=helper(node.left);
int right=helper(node.right);
ans+=Math.abs(left-right);
return left+right+node.val;
}
}