这里返回有两种形式,都用的递归

第一种:用结构返回,这种方法适合有多个变量的时候

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     struct res
13     {
14         int sum;
15         int tilt;
16     };
17     int findTilt(TreeNode* root) 
18     {
19         auto result=count(root);
20         return result.tilt;
21     }
22     
23     res count(TreeNode* root)
24     {
25         if(root==NULL)
26             return {0,0};
27         auto l=count(root->left);
28         auto r=count(root->right);
29         int sum=root->val+l.sum+r.sum;
30         int tilt=l.tilt+r.tilt+abs(l.sum-r.sum);
31         return {sum,tilt};
32     }
33 };

第二种:用一个全局变量返回

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 static int wing=[]()
11 {
12     std::ios::sync_with_stdio(false);
13     cin.tie(NULL);
14     return 0;
15 }();
16 
17 class Solution 
18 {
19 public:
20     int res=0;
21     int findTilt(TreeNode* root) 
22     {
23         count(root);
24         return res;
25     }
26     
27     int count(TreeNode* root)
28     {
29         if(root==NULL)
30             return 0;
31         int l=count(root->left);
32         int r=count(root->right);
33         res+=abs(l-r);
34         return root->val+l+r;
35     }
36 };

两种方法速度差不多,前一个没用加速函数,15ms,若添加加速函数,9ms

后一个速度和第一个相同,没加速15ms,加速后9ms

posted on 2018-06-05 11:50  高数考了59  阅读(110)  评论(0)    收藏  举报