Leetcode 563. Binary Tree Tilt

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/84945203

文章作者: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/

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试