Carregando

Problema do LeetCode#938

Range Sum of BST

Resolvido em 1 linguagemJava

Resolver no LeetCode(abre em uma nova aba)

Solução

34 linhas
1/**
2 * Definition for a binary tree node.
3 * public class TreeNode {
4 *     int val;
5 *     TreeNode left;
6 *     TreeNode right;
7 *     TreeNode() {}
8 *     TreeNode(int val) { this.val = val; }
9 *     TreeNode(int val, TreeNode left, TreeNode right) {
10 *         this.val = val;
11 *         this.left = left;
12 *         this.right = right;
13 *     }
14 * }
15 */
16class Solution {
17    public int rangeSumBST(TreeNode root, int low, int high) {
18        if (root == null) {
19            return 0;
20        }
21
22        int sum = 0;
23        if (root.val >= low && root.val <= high) {
24            sum += root.val;
25        }
26        if (root.val > low) {
27            sum += rangeSumBST(root.left, low, high);
28        }
29        if (root.val < high) {
30            sum += rangeSumBST(root.right, low, high);
31        }
32        return sum;
33    }
34}

Quer uma explicação desta solução em Java?

Receba uma explicação passo a passo da ideia por trás do código.

Todos os problemas

Os enunciados dos problemas pertencem ao LeetCode e estão em leetcode.com. Não temos vínculo com o LeetCode.