https://leetcode.com/problems/range-sum-of-bst/node
Given the root
node of a binary search tree, return the sum of values of all nodes with value between L
and R
(inclusive).數據結構
The binary search tree is guaranteed to have unique values.spa
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 Output: 32
翻譯:給一個BST,輸出L和R之間全部的節點值的和。翻譯
這道題其實只是掛着個Binary search tree的羊頭,賣的是遞歸的狗肉(也能夠用迭代去作,可是我感受出題者主要是想考察你遞歸的能力)。code
其實題的意思很簡單,就是讓你找這個root裏面全部大於L,小於R的值(包括L,R)的和。可是由於其數據結構是樹狀,因此必須用遞歸。遞歸
咱們先來看看數據結構:leetcode
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/get
很經典的樹狀。input
而後咱們來看答案,簡單的遞歸:it
class Solution
{
public int rangeSumBST(TreeNode root, int L, int R)
{
if (root == null) { return 0; }
int sum = 0;
if (root.val > L) { sum += rangeSumBST(root.left, L, R); }
if (root.val < R) { sum += rangeSumBST(root.right, L, R); }
if (root.val >= L && root.val <= R) { sum += root.val; }
return sum;
}
}
推薦閱讀:
遞歸和迭代的區別:https://www.jianshu.com/p/32bcc45efd32
還有遞歸的概念