leetcode.938. 二叉搜索树的范围和

leetcode.938. 二叉搜索树的范围和

深度优先搜索-官方

class Solution {
public:
    int rangeSumBST(TreeNode *root, int low, int high) {
        if (root == nullptr) {
            return 0;
        }
        if (root->val > high) {
            return rangeSumBST(root->left, low, high);
        }
        if (root->val < low) {
            return rangeSumBST(root->right, low, high);
        }
        return root->val + rangeSumBST(root->left, low, high) 
        + rangeSumBST(root->right, low, high);
    }
};

广度优先搜索-官方

class Solution {
public:
    int rangeSumBST(TreeNode *root, int low, int high) {
        int sum = 0;
        queue<TreeNode*> q({root});
        while (!q.empty()) {
            auto node = q.front();
            q.pop();
            if (node == nullptr) {
                continue;
            }
            if (node->val > high) {
                q.push(node->left);
            } else if (node->val < low) {
                q.push(node->right);
            } else {
                sum += node->val;
                q.push(node->left);
                q.push(node->right);
            }
        }
        return sum;
    }
};

中序遍历

#include <iostream>
#include <vector>
#include <stack>

using namespace std;

struct TreeNode {
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode() : val(0), left(nullptr), right(nullptr) {}
	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
	TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};


class Solution {
private:
	void ptree(TreeNode* node,vector<int> &vec) {
		if (node == nullptr) {
			return;
		}
		if (node->left != nullptr)ptree(node->left, vec);
		//cout << node->val << endl;
		vec.push_back(node->val);
		if (node->right != nullptr)ptree(node->right, vec);
	}
public:
	
	int rangeSumBST(TreeNode* root, int low, int high) {
		vector<int> vec;
		ptree(root,vec);
		//cout << " " << endl;
		int sum = 0;
		for (auto i : vec)
		{
			//cout << i << endl;
			if (i >= low && i <= high)sum += i;
		}
		return sum;
	}
};

int main()
{
	TreeNode* tr1 = new TreeNode(10);
	TreeNode* tr2 = new TreeNode(5);
	TreeNode* tr3 = new TreeNode(15);
	TreeNode* tr4 = new TreeNode(3);
	TreeNode* tr5 = new TreeNode(7);
	TreeNode* tr6 = new TreeNode(18);

	tr1->left = tr2;
	tr1->right = tr3;
	tr2->left = tr4;
	tr2->right = tr5;
	tr3->right = tr6;

	Solution s;
	cout << s.rangeSumBST(tr1, 7, 15) << endl;

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值