给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
如
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
输出:32
题目:二叉搜索树的范围和
或直转:https://leetcode-cn.com/problems/range-sum-of-bst/
- 我的题解
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void mybianli(struct TreeNode* root,int low,int high,int* sum){
if(root!=NULL){
if((root->val<=high)&&(root->val>=low)){
*sum+=root->val;
}
mybianli(root->left,low,high,sum);
mybianli(root->right,low,high,sum);
}
}
int rangeSumBST(struct TreeNode* root, int low, int high){
int base;
int* sum;
base=0;
sum=&base;
mybianli(root,low,high,sum);
return *sum;
}
感觉这题没什么可以说的,就是二叉树的遍历,也没涉及到二叉树的结点插入问题。传参最小最大范围,还有一个整型指针来指向和,因为存储的是地址,其指向内容不会被形参影响。没啥了,借用一下遍历的代码就行,中前后序无所谓。