257. Binary Tree Paths

来源:互联网 发布:h5 js 跳转到原生界面 编辑:程序博客网 时间:2024/05/22 15:10

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1 /   \2     3 \  5

All root-to-leaf paths are:

["1->2->5", "1->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) {if (root == NULL){return res;}vector<int> path;helper(root, path);return res;}private:void helper(TreeNode* root, vector<int>& path){path.push_back(root->val);if (root->left == NULL&&root->right == NULL){string p;int len = path.size();for (int i = 0; i < len; i++){if (i != len - 1){p += to_string(path[i]);p += "->";}else{p += to_string(path[i]);}}res.push_back(p);}if (root->left){helper(root->left, path);}if (root->right){helper(root->right, path);}path.pop_back();}vector<string> res;};

0 0