669. Trim a Binary Search Tree(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/82980791

题目:

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).You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.

Example 1:

Input: 
    1 
   / \   
  0   2
L = 1   R = 2
Output: 
    1
      \
       2 

Example 2:

Input: 
      3  
     / \  
    0   4   
     \
      2  
     /   
    1
 L = 1   R = 3
Output: 
     3
    /     
   2      
  /  
 1

解释:
重构二叉排序树,使得其值在所给范围之内。用递归来做。
BST的特点是父亲结点的左孩子都比它小,右孩子都比它大,所以如果父亲结点都比最小值小了,就不要左边所有的树了,仅仅返回右边的树的修剪的结果,同理,如果父亲结点都比最大值大了,就不要右边的树了,仅仅返回左边的修剪的结果。
左孩子等于左边修剪后的结果,右孩子等于右边修剪后的结果。
python代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def trimBST(self, root, L, R):
        """
        :type root: TreeNode
        :type L: int
        :type R: int
        :rtype: TreeNode
        """
        if (root):
            if root.val<L:
                return self.trimBST(root.right,L,R)
            elif root.val>R:
                return self.trimBST(root.left,L,R)
            else:
                root.left=self.trimBST(root.left,L,R)
                root.right=self.trimBST(root.right,L,R)
            	return root 
        return None

c++代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int L, int R) {
        if (root==NULL)
            return NULL;
        else if(root->val<L)
            return trimBST(root->right,L,R);
        else if(root->val>R)
            return trimBST(root->left,L,R);
        else
        {
            root->left=trimBST(root->left,L,R);
            root->right=trimBST(root->right,L,R);
            return root;
        }
    }
};

总结:
看到二叉树的时候,概率是递归了。

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/82980791