# [LeetCode] 257. Binary Tree Paths 二叉树路径

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"]

class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if (root) helper(root, "", res);
return res;
}
void helper(TreeNode* node, string out, vector<string>& res) {
if (!node->left && !node->right) res.push_back(out + to_string(node->val));
if (node->left) helper(node->left, out + to_string(node->val) + "->", res);
if (node->right) helper(node->right, out + to_string(node->val) + "->", res);
}
};

class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
if (!root) return {};
if (!root->left && !root->right) return {to_string(root->val)};
vector<string> left = binaryTreePaths(root->left);
vector<string> right = binaryTreePaths(root->right);
left.insert(left.end(), right.begin(), right.end());
for (auto &a : left) {
a = to_string(root->val) + "->" + a;
}
return left;
}
};

class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
if (!root) return {};
if (!root->left && !root->right) return {to_string(root->val)};
vector<string> res;
for (string str : binaryTreePaths(root->left)) {
res.push_back(to_string(root->val) + "->" + str);
}
for (string str : binaryTreePaths(root->right)) {
res.push_back(to_string(root->val) + "->" + str);
}
return res;
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/257

Path Sum II

https://leetcode.com/problems/binary-tree-paths/

https://leetcode.com/problems/binary-tree-paths/discuss/68258/Accepted-Java-simple-solution-in-8-lines

https://leetcode.com/problems/binary-tree-paths/discuss/68282/Clean-Java-solution-(Accepted)-without-any-helper-recursive-function

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2015-08-17 22:45  Grandyang  阅读(13829)  评论(5编辑  收藏  举报