LeetCode

链接

563. Binary Tree Tilt

题意

给定一个二叉树,返回这个二叉树的tilt
tilt:一个结点的tilt是指这个结点左子树所有结点和与右子树所有结点和的差的绝对值。

思路

利用递归,每个结点返回其所有(子)结点的和。设置一个全局变量累加每个结点的tilt值。

代码

Java 1:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int tilt = 0;
    public int findTilt(TreeNode root) {
        helper(root);
        return tilt;
    }
    
    public int helper(TreeNode root) {
        if (root == null) return 0;
        int sumLeft = helper(root.left);
        int sumRight = helper(root.right);
        tilt += Math.abs(sumLeft - sumRight);
        return root.val + sumLeft + sumRight;
    }
}

思考

没有直接利用递归求tilt值,而是设置了一个全局变量来进行累加

原文地址:https://www.cnblogs.com/zyoung/p/6846101.html