leetcode 563.二叉树的坡度

⭐️ 题目描述

leetcode 563.二叉树的坡度_第1张图片


leetcode链接:https://leetcode.cn/problems/binary-tree-tilt/description/

代码:

class Solution {
public:
    int childFind(TreeNode* root , int& sumTile) {
        if (root == nullptr) {
            return 0;   // 空树坡度为0
        }

        int leftChildVal = childFind(root->left , sumTile);
        int rightChildVal = childFind(root->right , sumTile);
        sumTile += abs(leftChildVal - rightChildVal);

        return root->val + leftChildVal + rightChildVal;
    }
    int findTilt(TreeNode* root) {
        int sumTile = 0;
        childFind(root , sumTile);
        
        return sumTile;
    }
};

递归展开图:
leetcode 563.二叉树的坡度_第2张图片


你可能感兴趣的:(刷题,leetcode,二叉树,学习)