zoukankan      html  css  js  c++  java
  • 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.

    题目含义: 这道题目给了我们一个二叉树,要我们求出二叉树的倾斜度。题目给了例子真的容易误导人。一开始以为只要求2个children的差值,其实是要求left 和 right 各自的总和,包括加上它们自己,left 和 right 两个总和值的差值。

     1     private int result=0;
     2     private int postOrder(TreeNode node)
     3     {
     4         if (node == null) return 0;
     5         int leftSum = postOrder(node.left);
     6         int rightSum = postOrder(node.right);
     7         result += Math.abs(leftSum-rightSum);
     8         return leftSum + rightSum +node.val;
     9     }
    10     public int findTilt(TreeNode root) {
    11        //        这道题目给了我们一个二叉树,要我们求出二叉树的倾斜度。题目给了例子真的容易误导人。一开始以为只要求2个children的差值,其实是要求left 和 right 各自的总和,包括加上它们自己,left 和 right 两个总和值的差值。利用post order 遍历二叉树,post order 的顺序是 左 右 根。这样的话就可以求出根的sum,左和右都return了以后,加上它自己的值。但是这样的recursively call 每次返回的都是一个点的sum 总值。我们需要求的是差值的总和。所以需要另外设一个res, 每次把差值加入res。
    12         postOrder(root);
    13         return result;
    14     }
  • 相关阅读:
    C# DES加密和解密
    SQL设计技巧优化
    MS15-034漏洞技术研究
    Vustudy靶场环境快速搭建
    FastJson<=1.2.47漏洞复现
    多台电脑共享一套鼠键--Mouse Without Borders
    {Java初级系列四}---继承、接口和抽象类
    {Java初级系列三}---面向对象和类
    {Java初级系列二}---Java类基础知识
    {Java初阶系列一}---Java基本简介
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7710731.html
Copyright © 2011-2022 走看看