Leetcode - 1022. Sum of Root To Leaf Binary Numbers

숲사람·2022년 5월 31일
0

멘타트 훈련

목록 보기
46/237

문제

0/1로만 구성된 Tree에서 root부터 leef까지 이어지는 노드순서가 이진수값을 나타낸다고 할때, 주어진 트리에서 나타낼수 있는 모든 값의 총 합을 구하라.

Input: root = [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22


https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/

해결

int recur(struct TreeNode* root, int val)
{
    int sum = 0; 
    
    if (root->left == NULL && root->right == NULL)
        return val;
    if (root->left)
        sum += recur(root->left, root->left->val + val * 2);
    if (root->right)
        sum += recur(root->right, root->right->val + val * 2);
    return sum;
}

int sumRootToLeaf(struct TreeNode* root){
    return recur(root, root->val);
}
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글