938. Range Sum of BST(python+cpp)

题目:

Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:

Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 
Output: 32 

Example 2:

Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 
Output: 23  

Note:
The number of nodes in the tree is at most 10000.
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 = None

class 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);
    } 
};

总结:
暴力中序遍历,恩

你可能感兴趣的:(LeetCode)