1. 程式人生 > 其它 >LeetCode 938. 二叉搜尋樹的範圍和

LeetCode 938. 二叉搜尋樹的範圍和

難度:簡單。
標籤:樹,深度優先搜尋,遞迴。

正確解法:

/**
 * 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 { int ans = 0; void getResult(TreeNode* cur, int low, int high){ if(cur == nullptr)return; if(cur->val >= low && cur->val <= high){ ans += cur->val; getResult(cur->right, low, high); getResult(cur->
left, low, high); } else if(cur->val < low)getResult(cur->right, low, high); else if(cur->val > high)getResult(cur->left, low, high); } public: int rangeSumBST(TreeNode* root, int low, int high) { getResult(root, low, high); return ans;
} };

結果:
在這裡插入圖片描述