• 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 }
  • 相关阅读:
    Nginx
    Haproxy
    Magento学习笔记2 createEntityType方法失效!
    PHP手册阅读笔记
    转载数据库设计
    PHP文件操作函数
    Magento学习笔记1
    PHP手册阅读笔记2
    C++疑惑
    定时任务quartz源码
  • 原文地址:https://www.cnblogs.com/zle1992/p/7749464.html
Copyright © 2020-2023  润新知