1. 程式人生 > >Leetcode938. Range Sum of BST二叉搜尋樹的範圍和

Leetcode938. Range Sum of BST二叉搜尋樹的範圍和

給定二叉搜尋樹的根結點 root,返回 L 和 R(含)之間的所有結點的值的和。

二叉搜尋樹保證具有唯一的值。

 

示例 1:

輸入:root = [10,5,15,3,7,null,18], L = 7, R = 15 輸出:32

示例 2:

輸入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 輸出:23

 

提示:

  1. 樹中的結點數量最多為 10000 個。
  2. 最終的答案保證小於 2^31。

 

 

二叉樹有關的一般都是遞迴求解

 

 class Solution {
 public:
	 int rangeSumBST(TreeNode* root, int L, int R)
	 {
		 if (root == NULL)
			 return 0;
		 if (root->val < L)
		 {
			 return rangeSumBST(root->right, L, R);
		 }
		 else if (root->val > R)
		 {
			 return rangeSumBST(root->left, L, R);
		 }
		 else
		 {
			 return root->val + rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R);
		 }
	 }
 };