一、題目描述spa
Given a binary search tree and the lowest and highest boundaries as L
and R
, trim the tree so that all its elements lies in [L, R]
(R >= L).code
You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.blog
題目的意思是給定一個二叉查找樹,和兩個值。刪除掉樹中全部不在兩個值範圍內的節點。遞歸
二、題目分析element
因爲二叉查找樹的遞歸定義和數據有序的特色,使用遞歸方法解決二叉查找樹是比較理想的。it
三、代碼class
1 TreeNode* trimBST(TreeNode* root, int L, int R) { 2 3 if( root == NULL ) 4 return NULL; 5 6 if( root->val < L ) 7 { 8 return trimBST(root->right,L,R); 9 } 10 11 if(root->val > R ) 12 { 13 return trimBST(root->left,L,R); 14 } 15 16 root->left = trimBST(root->left,L,R); 17 root->right = trimBST(root->right,L,R); 18 19 return root; 20 21 }