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.

    求二叉树的倾斜

    树节点的倾斜被定义为所有左子树节点值和所有右子树节点值的和的绝对差。零节点有倾斜0。

    C++(22ms):

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int findTilt(TreeNode* root) {
    13         if (root == NULL)
    14             return 0 ;
    15         int res = 0 ;
    16         tilt(root,res) ;
    17         return res ;
    18     }
    19     
    20     int tilt(TreeNode* root , int& res) {
    21         if (root == NULL)
    22             return 0 ;
    23         int leftSum = tilt(root->left,res) ;
    24         int rightSum = tilt(root->right,res) ;
    25         res += abs(leftSum-rightSum) ;
    26         return leftSum + rightSum + root->val ;
    27     }
    28 };
  • 相关阅读:
    MVC框架及应用
    《架构之美》三
    《架构之美》二
    深度学习之多层感知器
    架构之美
    质量属性之淘宝案例分析
    配置cocos相关问题
    3-5
    web文本框之内容提示
    【LeetCode】024. Swap Nodes in Pairs
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8072680.html
Copyright © 2011-2022 走看看