LeetCode题解之Binary Tree Tilt

1、题目描述

2、分析

利用递归实现。

3、代码

 1 int findTilt(TreeNode* root) {
 2         if (root == NULL)
 3             return 0;
 4          int ans = 0;  
 5         nodesTilt(root,ans);
 6         return ans; 
 7     }
 8     
 9     int nodesTilt(TreeNode *root, int & ans)
10     {
11         if (root == NULL)
12             return 0;
13         int tiltleft = nodesTilt(root->left, ans);
14         int tiltright = nodesTilt(root->right, ans);
15         ans += abs(tiltleft - tiltright);
16         return tiltleft + tiltright + root->val;
17     }
18     

猜你喜欢

转载自www.cnblogs.com/wangxiaoyong/p/10436561.html