-
[LeetCode] 563. Binary Tree TiltLeetCode 2021. 12. 8. 11:47728x90
https://leetcode.com/problems/binary-tree-tilt/
Binary Tree Tilt - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Binary Tree Tilt - Easy



binary tree에서 각각의 노드의 tilt의 합을 구하는 문제다.
노드의 tilt란 왼쪽 모든 하위노드들의 합과 오른쪽 모든 하위노드들의 합의 차이를 의미한다.
먼저 최하위 노드로 가서 결과값에 0을 더해준다. (최하위는 자식노드들이 없으므로)
그 다음, 그 위 노드로 가서 양쪽 노드의 값을 해당 노드에 더해주고, tilt를 구해 결과값에 더해준다.
그리고 또 위 노드로 가서 해당작업을 반복한다.
즉, 아래부터 계산이 이뤄져야 한다.
전체 풀이 코드
class Solution { public: int s=0; int findTilt(TreeNode* root) { run(root); return s; } void run(TreeNode* node) { if (!node) return; run(node->left); run(node->right); int l=0, r=0; if (node->left) node->val += node->left->val, l=node->left->val; if (node->right) node->val += node->right->val, r=node->right->val; s += abs(l-r); } };'LeetCode' 카테고리의 다른 글
[LeetCode] 394. Decode String (0) 2021.12.19 [LeetCode] 1306. Jump Game III (0) 2021.12.09 [LeetCode] 120. Triangle (0) 2021.12.03 [LeetCode] 328. Odd Even Linked List (0) 2021.12.02 [LeetCode] 198. House Robber (0) 2021.12.01