LeetCode(257)Binary Tree Paths

来源:互联网 发布:mac键盘灯不亮 编辑:程序博客网 时间:2024/05/22 17:22

c++代码如下

/** * 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:    void tra(TreeNode *root, string &path, vector<string> &result) {        if(root->left == NULL && root->right == NULL) { string tmp = path; path += to_string(root->val); result.push_back(path); path = tmp; return; }        string tmp = path;        path = path + to_string(root->val);        path += "->";        if(root->left) tra(root->left, path, result);        if(root->right) tra(root->right, path, result);        path = tmp;    }    vector<string> binaryTreePaths(TreeNode* root) {        vector<string> result;        string path;        if(root == NULL) return result;        tra(root, path, result);        return result;    }};
0 0
原创粉丝点击