2019年2月25日 Range Sum of BST

binary search tree (BST) 二分树的基本方法,search,insert,MAX,MIN,delete概念复习下,这道题简单的递归搜索可以解决。


/**
 * 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 rangeSumBST(TreeNode* root, int L, int R) {
        int leftSum = 0;
        int rightSum = 0;
        if (root->val > L && root->left != NULL) 
        {
            leftSum = rangeSumBST(root->left, L, R);
        }
        if (root->val < R && root->right != NULL)
        {
            rightSum = rangeSumBST(root->right, L, R);
        }
        if (L <= root->val && root->val <= R){
            return leftSum + rightSum + root->val;
        }
        return leftSum + rightSum;
    }
};

posted @ 2019-02-25 09:22  miuc  阅读(193)  评论(0编辑  收藏  举报