코테준비 - Binary Tree Paths

정상화·2023년 3월 5일

LeetCode

목록 보기
213/222

Binary Tree Paths

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode *root) {
        string history;
        vector<string> result;
        dfs(result, history, root);
        return result;
    }

    void dfs(vector<string> &res, string history, TreeNode *node){
        history += to_string(node->val);

        if (!node->left && !node->right) {
            res.push_back(history);
            return;
        }
        if (node->left) {
            dfs(res, history + "->", node->left);
        }
        if (node->right) {
            dfs(res, history + "->", node->right);
        }
    }
};
profile
백엔드 희망

0개의 댓글