1.原題:
https://leetcode.com/problems/range-sum-of-bst/
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.
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
翻譯:給一個BST,輸出L和R之間所有的節點值的和,
2.解題思路:
這道題其實只是掛著個Binary search tree的羊頭,賣的是遞回的狗肉(也可以用迭代去做,但是我感覺出題者主要是想考察你遞回的能力),
其實題的意思很簡單,就是讓你找這個root里面所有大于L,小于R的值(包括L,R)的和,但是因為其資料結構是樹狀,所以必須用遞回,
我們先來看看資料結構:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
很經典的樹狀,
然后我們來看答案,簡單的遞回:
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
還有遞回的概念
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/41071.html
標籤:其他
下一篇:不備案的網站需要用什么用的服務器
