Try   HackMD

938. Range Sum of BST


My Solution

The Key Idea for Solving This Coding Question

C++ Code 1

/** * 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) { int answer = 0; dfs(root, low, high, answer); return answer; } private: void dfs(TreeNode *root, int low, int high, int &answer) { if (root == nullptr) { return; } if (root->val < low) { dfs(root->right, low, high, answer); return; } if (high < root->val) { dfs(root->left, low, high, answer); return; } answer += root->val; dfs(root->left, low, high, answer); dfs(root->right, low, high, answer); } };

Time Complexity

O(n)
n
is the number of nodes in the binary tree referred by root.

Space Complexity

O(H)
H
is the height of the binary tree referred by root.

C++ Code 2

/** * 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); } if (high < root->val) { return rangeSumBST(root->left, low, high); } return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high); } };

Time Complexity

O(n)
n
is the number of nodes in the binary tree referred by root.

Space Complexity

O(H)
H
is the height of the binary tree referred by root.

Miscellane