1. 程式人生 > >938. Range Sum of BST(python+cpp)

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

總結:
暴力中序遍歷,恩