leetcode: 669. Trim a Binary Search Tree

题目解析:

题目链接:https://leetcode.com/problems/trim-a-binary-search-tree/description/

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.

给一个二叉搜索树,高低边界为L和R,修剪该二叉树使得其所有元素都在[L,R]区间里。你可能需要修改二叉树的根,所以结果必须返回修剪后二叉树的新根。

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
解题思路:

我做这类题目时偏好于新建一棵树,将符合条件的节点赋给新树。因此,遍历原树,如果节点符合边界条件,就赋给新树,如果不符合,就接着遍历,并且新树不参与遍历。

代码如下:

void trim(treeNode* root, treeNode* &root1, int L, int R)
{
	if (!root)
		return;

	if (root->val >= L&&root->val <= R)
	{
		root1 = new treeNode;
		root1->val = root->val;
		trim(root->left, root1->left, L, R);
		trim(root->right, root1->right, L, R);
	}
	else
	{
		if (root->left)
		{
			
			trim(root->left, root1, L, R);
				
		}
		if (root->right)
		{
			
			trim(root->right, root1, L, R);
				
		}
	}
}
treeNode* trimBST(treeNode* root, int L, int R) {
	treeNode* root1;
	trim(root, root1, L, R);
	return root1;
}

网上有人给出了在原树直接操作的代码,我贴上来学习一下。自己代码的不足在于没考虑二叉搜索树节点值之间的大小关系。简洁代码的思路是如果节点值在边界范围内,就把问题递归到左右子树。如果节点值root->val>R那么由于二叉树右子树所有节点值都比根节点大,因此,把整个右子树舍弃。如果节点值root->val<L,由于二叉树左子树所有节点值都比根节点小,因此,把整个右子树舍弃。

/**
 * 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;
        if(root->val > R)
            return trimBST(root->left, L, R);
        if(root->val < L)
            return trimBST(root->right, L, R);
        root->left = trimBST(root->left, L, R);
        root->right = trimBST(root->right, L, R);
        return root;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值