본문 바로가기
알고리즘 문제풀이/leetcode

[leetcode 1022] Sum of Root To Leaf Binary Numbers

by m2162003 2020. 10. 3.

You are given the root of a binary tree where each node has a value 0 or 1.  Each root-to-leaf path represents a binary number starting with the most significant bit.  For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.

For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.

Return the sum of these numbers. The answer is guaranteed to fit in a 32-bits integer.

 

Example 1:

Input: root = [1,0,1,0,1,0,1]

Output: 22

Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

 

Example 2:

Input: root = [0] Output: 0

 

Example 3:

Input: root = [1] Output: 1

 

Example 4:

Input: root = [1,1] Output: 3

 

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • Node.val is 0 or 1.

- 큐를 이용한 트리 순회

- 누적값을 저장해야 하기 때문에 pair를 만들어서 <노드 포인터,  누적값>을 저장한다.

- 더 이상 자식 노드가 없으면 해당 노드가 leaf node이기 때문에 이 경우에 정답값 result에 누적값을 더한다. 

- 한쪽이라도 자식 노드가 있으면 push를 하기 때문에 현재 노드가 nullptr인지 확인하는 작업이 필수!

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumRootToLeaf(TreeNode* root) {
        
        int result = 0;
        
        queue<pair<TreeNode*, int>> q;
        q.push(make_pair(root, 0));
        
        while(!q.empty()){
            TreeNode* curNode = q.front().first;
            int curSum = q.front().second;
            q.pop();
            
            if(curNode != nullptr){
                curSum = curSum*2 + (curNode->val);
                
                //if curNode is leaf then return value
                 if(curNode -> left == nullptr && curNode -> right == nullptr){
                    result += curSum;
                 }
                 else{
                    q.push(make_pair(curNode->left, curSum));
                    q.push(make_pair(curNode->right, curSum));
                 }
            }
        
        }
        
        return result;
        
    }
};

댓글