1022. Sum of Root To Leaf Binary Numbers

Sum of Root To Leaf Binary Numbers

 

Sum of Root To Leaf Binary Numbers - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

-문제 내용:

Leaf 까지의 Binary 수를 string으로 누적해서 integer value를 만들고 모든 value를 Sum 해라

- 접근 방법 : DFS

var sumRootToLeaf = function(root, val = '') {
    if(root == null) return 0;
    let result = 0;
    if(root.left != null) result += sumRootToLeaf(root.left, val + root.val);
    if(root.right != null) result += sumRootToLeaf(root.right, val + root.val);
    
    if(root.left == null && root.right == null){
        return parseInt(val+root.val,2);  
    }
    
    return result;
};

 

728x90
반응형