-
[LeetCode] 938. Range Sum of BST c++Coding Test/LeetCode 2022. 9. 26. 18:11728x90
- 문제
Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].
이진탐색트리의 node중에 low와 high사이에 있는 값을 모두 더한 값을 구하는 문제이다.
- 문제 해결
class Solution { public: int nSum = 0; int rangeSumBST(TreeNode* root, int low, int high) { if(root == NULL) return nSum; if(root->val >= low && root-> val <= high){ nSum += root->val; } rangeSumBST(root->left, low, high); rangeSumBST(root->right, low, high); return nSum; } };
다른 방법
int rangeSumBST(TreeNode* root, int L, int R) { int rangeSum(0); stack<TreeNode*> st; st.push(root); while(!st.empty()){ TreeNode* node = st.top(); st.pop(); if(node->val>=L && node->val<=R) rangeSum+=node->val; if(node->val > L) {if(node->left) st.push(node->left);} if(node->val < R) {if(node->right) st.push(node->right);} } return rangeSum; }
728x90'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 617. Merge Two Binary Trees c++ (0) 2022.09.27 [LeetCode] 2331. Evaluate Boolean Binary Tree c++ (0) 2022.09.26 [LeetCode] 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree c++ (0) 2022.09.26 [LeetCode] 27. Remove Element c++ (0) 2022.09.15 [LeetCode] 26. Remove Duplicates from Sorted Array c++ (0) 2022.09.15