[leetcode #1022] Sum of Root To Leaf Binary Numbers

Seongyeol Shin·2022년 1월 11일
0

leetcode

목록 보기
129/196
post-thumbnail

Problem

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 test cases are generated so that the answer fits 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

Constraints:

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

Idea

리프 노드일 경우 루트 노드부터 시작해서 리프노드까지 오기까지의 수를 이진수로 만들어 전체 합을 구하는 문제다.

트리 관련 문제답게 재귀함수로 풀면 쉽다. 우선 노드가 null일 경우 0을 리턴하게 하고, 노드가 리프 노드일 경우는 인자로 넘어온 값의 2배에 현재 노드의 값을 더해 리턴하면 된다. 인자로 넘겨주는 값은 루트 노드부터 시작해 더해지는 값으로 left shift할 때 2배가 되므로, 리프 노드가 나왔을 때 2배로 만들어준다.

리프 노드가 아닐 경우도 리프 노드와 똑같이 하면 되는데, 값을 리턴하는 게 아니고 인자로 넣어주는 값을 조정하면 된다. 넘겨받은 값을 2배로 해주고 현재 노드의 값을 더해 인자로 넘겨주면 자식 노드가 리프노드가 될 때까지 값을 올바르게 계산할 수 있다.

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int sumRootToLeaf(TreeNode root) {
        return traverse(root, 0);
    }

    private int traverse(TreeNode node, int val) {
        if (node == null) {
            return 0;
        }

        if (node.left == null && node.right == null) {
            return node.val + 2 * val;
        }

        return traverse(node.left, 2 * val + node.val) + traverse(node.right, 2 * val + node.val);
    }
}

Reference

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

profile
서버개발자 토모입니다

0개의 댓글