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     }
  • 相关阅读:
    jQuery 图片剪裁插件初探之 Jcrop
    Android中如何使用对话框(单选对话框和多选对话框)
    Android中如何使用对话框(单选对话框和多选对话框)
    Android中如何使用GridView
    Android中如何使用GridView
    Android中如何使用GridView
    Android中如何使用GridView
    Android中如何使用Listview
    Android中如何使用Listview
    Android中如何使用Listview
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7710731.html
Copyright © 2011-2022 走看看