257. Binary Tree Paths

1.問題

  • 回傳所有root-to-leaf path

2.想法

  • preorder traversal

3.程式碼

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        vector<int> record;
        preorder(res, record, root);
        return res;
    }
private:
    void preorder(vector<string>& res, vector<int> record, TreeNode* root) {
        if (root) {
            record.push_back(root->val);
            if (!root->left && !root->right) {
                string tmp = to_string(record[0]);
                for (int i = 1; i < record.size(); i++) {
                    tmp = tmp + "->" + to_string(record[i]);
                }
                res.push_back(tmp);
            }
            preorder(res, record, root->left);
            preorder(res, record, root->right);
            
        }
    }
};

Last updated