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 }
  • 相关阅读:
    Linux配置防火墙 开启80端口
    微信支付调用JSAPI缺少参数:timeStamp
    php解压zip文件
    css JavaScript 笔记
    css
    html标签
    模拟服务器返回html
    网页特殊符号HTML代码大全
    selectors模块
    select
  • 原文地址:https://www.cnblogs.com/zle1992/p/7749464.html
Copyright © 2011-2022 走看看