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.

    思路: 
    这道题其实是要求 求出各个节点左右子树的差的绝对值,将这些绝对值求和并返回。 
    左右子树的差 = | 左子树所有节点的值的和 - 右子树所有节点的值的和 | 
    (刚开始没好好看题,只算了各个节点左右孩子的差,导致一直出错)

     1 class Solution {
     2     int SUM = 0;
     3     public int findTilt(TreeNode root) {
     4         postOrder(root);
     5         return SUM;
     6         
     7     }
     8       public int postOrder(TreeNode root) {
     9         if(root == null) return 0;
    10         int left = postOrder(root.left);
    11         int right =postOrder(root.right);
    12     
    13         SUM += Math.abs(left - right);
    14  
    15         return left + right+root.val;
    16         
    17     }
    18 }
  • 相关阅读:
    2020系统综合实践 第三次实践作业
    2020系统综合实践 第二次实践作业
    2020系统综合实践 第一次实践作业
    第03组 Beta版本演示
    第03组 Beta冲刺(4/4)
    第03组 Beta冲刺(3/4)
    OO第四次博客作业
    OO第三次博客作业
    OO第二次博客作业
    OO第一次博客作业
  • 原文地址:https://www.cnblogs.com/zle1992/p/7749464.html
Copyright © 2011-2022 走看看