[LeetCode By Go 41]563. Binary Tree Tilt

题目

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)

二叉树节点的倾斜值是指其左右子树和的差的绝对值。空节点的倾斜值为0。

注意

  1. 节点和不超过32位整数范围
  2. 倾斜值不超过32位整数范围

解题思路

遍历二叉树,求二叉树子树的和
累加各子树的倾斜值,得到二叉树的倾斜值

代码

findTilt.go

package _563_Binary_Tree_Tilt

import "math"

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

var tilt int
func subTreeSum(t *TreeNode) (sum int){
    if nil == t {
        return 0
    }

    left := subTreeSum(t.Left)
    right := subTreeSum(t.Right)

    tilt += int(math.Abs((float64(left) - float64(right))))

    return t.Val + left + right
}
func FindTilt(root *TreeNode) int {
    tilt = 0
    subTreeSum(root)
    return tilt
}

测试

findTilt_test.go

package _563_Binary_Tree_Tilt

import "testing"

func InitTree(index int, input []int) (t *TreeNode) {
    if index > len(input) {
        return nil
    }

    t = new(TreeNode)
    t.Val = input[index - 1]

    t.Left = InitTree(index*2, input)
    t.Right = InitTree(index*2 + 1, input)

    return t
}

func TestFindTilt(t *testing.T) {
    input1 := []int{1,2,3}

    var tests = []struct{
        tree *TreeNode
        output int
    }{
        {InitTree(1, input1), 1},
    }

    for _, test := range tests {
        ret := FindTilt(test.tree)

        if ret == test.output {
            t.Logf("pass")
        } else {
            t.Errorf("fail, want %+v, get %+v", test.output, ret)
        }
    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/2249c6cd8127
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞