728x90
left leave๋ฅผ ๋ง๋ ๋์ ์กฐ๊ฑด์ ํด๋น node์ left์ right๊ฐ ๋ชจ๋ null ์ธ ๊ฒฝ์ฐ ์ด๋ฏ๋ก ํด๋น ์กฐ๊ฑด์ผ ๋ return ํ๊ณ ์๋ ๊ฒฝ์ฐ๋ ๋ชจ๋ ํ์ํด์ ๋ค์ด๊ฐ๋ฉด ๋๋ค.
/**
* 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 sumOfLeftLeaves(TreeNode* root) {
return travernode(root);
}
int travernode(TreeNode* node) {
if(node == NULL)
return 0;
return traverLeft(node->left) + traverRight(node->right);
}
int traverLeft(TreeNode* node) {
if(node == NULL)
return 0;
if(node->left == NULL && node->right == NULL)
return node->val;
return traverLeft(node->left) + traverRight(node->right);
}
int traverRight(TreeNode* node) {
if(node == NULL)
return 0;
return traverLeft(node->left) + traverRight(node->right);
}
};
'๐ Self Study > ๐ LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
LeetCode (Add two numbers) C++ (0) | 2022.01.07 |
---|---|
LeetCode (Two Sum) C++ (0) | 2022.01.07 |
LeetCode (Employee Importance) C++ (0) | 2022.01.06 |