Binary search tree가 주어졌을 때, L과 R 사이에 있는 모든 노드 Value의 총합을 구해라
모든 트리는 유니크하다
Pyhton
class Solution:
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
self.result=0
def recurs(root,L,R):
if root.val >= L and root.val <= R:
self.result+=root.val
if root.left!=None : recurs(root.left,L,R)
if root.right!=None : recurs(root.right,L,R)
recurs(root,L,R)
return self.result
Javascript
var rangeSumBST = function(root, L, R) {
let result = 0;
let recurs = (node) => {
if(node.val >= L && node.val <= R) result+=node.val
if(node.left !== null) recurs(node.left)
if(node.right !== null) recurs(node.right)
}
recurs(root)
return result
};
댓글