MayUWell

Learn, Sleep, Learn

563-Binary Tree Tilt

Description

Given a binary tree, return the tilt of the whole tree.

The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.

The tilt of the whole tree is defined as the sum of all nodes’ tilt.


Example:

Input: 
         1
       /   \
      2     3
Output: 1
Explanation: 
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1

Note:

  1. The sum of node values in any subtree won’t exceed the range of 32-bit integer.
  2. All the tilt values won’t exceed the range of 32-bit integer.

问题描述

给定二叉树, 返回整棵树的tilt

一个节点的tilt为其左子树节点之和与右子树节点之和的差值的绝对值。空节点的tilt为0

整棵树的tilt为其所有子节点的tilt之和


问题分析

后续遍历, 求出当前节点的左子树之和left, 右子树之和right, 累加left - right的绝对值, 返回left + right + root.val(root为当前节点)


解法

class Solution {
    private int tilt = 0;

    public int findTilt(TreeNode root) {
        getSum(root);

        return tilt;
    }

    public int getSum(TreeNode root){
        if(root == null) return 0;

        int left = getSum(root.left);
        int right = getSum(root.right);
        tilt += Math.abs(left - right);

        return left + right + root.val;
    }
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LaputaFallen/article/details/80147808
个人分类: 算法与数据结构
所属专栏: leetcode全解
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭