LeetCode-563. Binary Tree Tilt

本文介绍了如何使用三种不同的C++实现方法来计算给定二叉树的所有节点的倾斜总和。通过递归的方式,每种方法都展示了独特的计算左右子树节点值之和及其绝对差值的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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.

Solution 1(C++)

static int x=[](){std::ios::sync_with_stdio(false); cin.tie(NULL); return 0;}();
class Solution {
public:
    int subTreeSum(TreeNode* node){
        if(!node) return 0;
        return node->val+subTreeSum(node->left)+subTreeSum(node->right);
    }
    int findTilt(TreeNode* root) {
        if(!root) return 0;
        return abs(subTreeSum(root->right)-subTreeSum(root->left))+findTilt(root->left)+findTilt(root->right);
    }
};

Solution 2(C++)

class Solution {
public:
    int findTilt(TreeNode* root) {
        int totalTilt = 0, sum = 0;
        sumTree(root, totalTilt);
        return totalTilt;
    }

    int sumTree(TreeNode* root, int& totalTilt) {
        if (root) {
            int ls = sumTree(root->left, totalTilt);
            int rs = sumTree(root->right, totalTilt);
            totalTilt += abs(ls - rs);
            return ls + rs + root->val;
        }
        return 0;
    }
}

Solution 3(C++)

int x = []() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(nullptr);
  return 0;
}();

class Solution {
  struct Result {
    int sum;
    int tilt;
  };

  Result traverse(TreeNode* root) {
    if (!root) return {0, 0};
    auto l = traverse(root->left);
    auto r = traverse(root->right);
    int tilt = std::abs(l.sum - r.sum) + l.tilt + r.tilt;
    int sum = l.sum + r.sum + root->val;
    return {sum, tilt};
  }
 public:
  int findTilt(TreeNode* root) {
    auto result = traverse(root);
    return result.tilt;
  }
};

算法分析

解法一是自己写的,,形式比较简单,但是好像算法比较复杂。其实是有部分重复,比如计算左右子树的节点和,可直接计算题目要求的那个值。

程序分析

感觉树的习题能很好锻炼递归,深度优先,广度优先等等。需要回头多做一做。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值