669. Trim a Binary Search Tree

两种递归写法

第一种递归,通过循环找准当前节点

 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 
11 static int wing=[]()
12 {
13     std::ios::sync_with_stdio(false);
14     cin.tie(NULL);
15     return 0;
16 }();
17 
18 class Solution 
19 {
20 public:
21     TreeNode* trimBST(TreeNode* root, int L, int R) 
22     {
23         if(root==NULL)
24             return NULL;
25         while(root!=NULL&&(root->val>R||root->val<L))
26         {
27             if(root->val>R)
28                 root=(root->left==NULL)? NULL:root->left;
29             if(root!=NULL&&root->val<L)
30                 root=(root->right==NULL)? NULL:root->right;
31         }
32         if(root!=NULL)
33         {
34             if(root->left!=NULL)
35                 root->left=trimBST(root->left,L,R);
36             if(root->right!=NULL)
37                 root->right=trimBST(root->right,L,R);
38         }
39         return root;
40     }
41 };

第二种递归,通过递归调用本身来找到当前节点

 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 
11 static int wing=[]()
12 {
13     std::ios::sync_with_stdio(false);
14     cin.tie(NULL);
15     return 0;
16 }();
17 
18 class Solution 
19 {
20 public:
21     TreeNode* trimBST(TreeNode* root, int L, int R) 
22     {
23         if(root!=NULL)
24         {
25             if(root->val>R)
26                 return trimBST(root->left,L,R);
27             else if(root->val<L)
28                 return trimBST(root->right,L,R);
29             else
30             {
31                 root->left=trimBST(root->left,L,R);
32                 root->right=trimBST(root->right,L,R);
33             }
34         }
35         else
36             return NULL;
37         return root;
38     }
39 };

猜你喜欢

转载自www.cnblogs.com/zhuangbijingdeboke/p/9157483.html