美文网首页Leetcode
Leetcode 563. Binary Tree Tilt

Leetcode 563. Binary Tree Tilt

作者: SnailTyan | 来源:发表于2018-12-10 19:44 被阅读3次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Binary Tree Tilt

2. Solution

/**
 * 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 findTilt(TreeNode* root) {
        if(!root) {
            return 0;
        }
        int tilt = 0;
        dfs(root, tilt);
        return tilt;
    }
    
private:
    int dfs(TreeNode* root, int& tilt) {
        if(!root) {
            return 0;
        }
        int leftSum = dfs(root->left, tilt);
        int rightSum = dfs(root->right, tilt);
        tilt += abs(leftSum - rightSum);
        return root->val + leftSum + rightSum;
    }
};

Reference

  1. https://leetcode.com/problems/binary-tree-tilt/description/

相关文章

网友评论

    本文标题:Leetcode 563. Binary Tree Tilt

    本文链接:https://www.haomeiwen.com/subject/cabdhqtx.html