本文共 1764 字,大约阅读时间需要 5 分钟。
题目:
Given the
The binary search tree is guaranteed to have unique values. Example 1:root
node of a binary search tree, return the sum of values of all nodes with value betweenL
andR
(inclusive).Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 Output: 32Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 Output: 23Note:
The number of nodes in the tree is at most10000
. The final answer is guaranteed to be less than 231.
解释:
中序遍历。 python代码:# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: def rangeSumBST(self, root, L, R): """ :type root: TreeNode :type L: int :type R: int :rtype: int """ self.sum=0 def mid(root): if root.left: mid(root.left) if root.val>=L and root.val<=R: self.sum+=root.val if root.right: mid(root.right) if root: mid(root) return self.sum
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: int global_sum=0; int global_L; int global_R; int rangeSumBST(TreeNode* root, int L, int R) { global_L=L; global_R=R; if (root) mid(root); return global_sum; } void mid(TreeNode* root) { if (root->left) mid(root->left); if(root->val>=global_L && root->val<=global_R) global_sum+=root->val; if(root->right) mid(root->right); } };
总结:
暴力中序遍历,恩转载地址:http://srlcn.baihongyu.com/