๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš“ Self Study/๐Ÿ”“ LeetCode

LeetCode (Sum of Left Leaves) C++

by UKHYUN22 2022. 1. 6.
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