본문 바로가기
Problem Solving/LeetCode

[LeetCode] 563. Binary Tree Tilt - Java

by graycode 2026. 9. 2.

• 문제 링크

 

Binary Tree Tilt - LeetCode

Can you solve this real interview question? Binary Tree Tilt - Given the root of a binary tree, return the sum of every tree node's tilt. The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtr

leetcode.com

 

• 풀이 코드

public class Solution {

    int sum = 0;

    public int findTilt(TreeNode root) {
        sum(root);
        return sum;
    }

    private int sum(TreeNode node) {
        if (node == null) return 0;

        int l = sum(node.left), r = sum(node.right);
        sum += Math.abs(l - r);

        return l + r + node.val;
    }

}

댓글