zoukankan      html  css  js  c++  java
  • leetcode 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:
    
    The sum of node values in any subtree won't exceed the range of 32-bit integer.
    All the tilt values won't exceed the range of 32-bit integer.
    
    

    深搜的时候记录左子树右子树的和,然后做差求和。

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int sum = 0;
        int dfs(TreeNode* root) {
            if (root == nullptr) return 0;
            if (root->left == nullptr && root->right == nullptr) return root->val;
            int sum1 = 0;
            int sum2 = 0;
            sum1 += dfs(root->left);
            sum2 += dfs(root->right);
            sum += abs(sum1 - sum2);
            return sum1+sum2+root->val;
        }
        int findTilt(TreeNode* root) {
            dfs(root);
            return sum;
        }
    };
    
  • 相关阅读:
    字符编码笔记:ASCII,Unicode 和 UTF-8
    nginx 负载均衡设置
    ubuntu 修改时区
    js 高阶函数 filter
    js 高阶函数 map reduce
    省市联级菜单--js+html
    php代码优化技巧
    json、xml ---- 数据格式生成类
    初识设计模式(1)---单例、工厂、注册树
    php 链式操作的实现 学习记录
  • 原文地址:https://www.cnblogs.com/pk28/p/8486777.html
Copyright © 2011-2022 走看看