본문 바로가기

Algorithm/자료구조

(C++) - LeetCode (easy) 563. Binary Tree Tilt

반응형

https://leetcode.com/problems/binary-tree-tilt/description/

 

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

자료구조 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

왼쪽과 오른쪽 subtree의 누적합을 저장할 변수 sum을 선언 후 0으로 초기화해줍니다.

📔 풀이과정

1. 왼쪽과 오른쪽 subtree를 재귀적으로 순회해줍니다.

2. 왼쪽 tree와 오른쪽 tree의 현 node에 대한 절댓값을 저장해줍니다.

📔 정답 출력 | 반환

sum을 반환합니다.


📕 Code

📔 C++

/**
 * 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 sum=0;
    int makeTilt(TreeNode*root){
        if(root == NULL) return 0;
        int l = makeTilt(root -> left);
        int r = makeTilt(root -> right);
        sum += abs(l - r);
        return root->val + l + r;
    }

    int findTilt(TreeNode* root) {
        makeTilt(root);
        return sum;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.