码迷,mamicode.com
首页 > 其他好文 > 详细

669. Trim a Binary Search Tree

时间:2018-06-08 22:01:03      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:ati   pre   cin   false   bin   struct   search   tree   null   

两种递归写法

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

 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 };

 

669. Trim a Binary Search Tree

标签:ati   pre   cin   false   bin   struct   search   tree   null   

原文地址:https://www.cnblogs.com/zhuangbijingdeboke/p/9157483.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!