-
[leetcode] 938. Range Sum of BST알고리즘 2021. 3. 20. 11:47728x90
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int rangeSumBST(TreeNode* root, int low, int high) { if(!root) return 0; if(root->val < low) return rangeSumBST(root->right, low, high); else if(low <= root->val && root->val <= high) return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high); else return rangeSumBST(root->left, low, high); } };
단순 Recursion으로 구현
시간복잡도 : O(n)
다른사람들 풀이는 Inorder Traversal 사용하던데 큰 차이는 없을듯
'알고리즘' 카테고리의 다른 글
[LEETCODE] 34. Find First and Last Position of Element in Sorted Array (0) 2021.04.08 [leetcode] 84. Largest Rectangle in Histogram (0) 2021.03.29 [leetcode] 18. 4Sum (0) 2021.03.29 [leetcode] 295. Find Median from Data Stream (0) 2021.03.25 [leetcode] 41. First Missing Positive (0) 2021.03.25