我用的递归,代码如下:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the root of the binary tree
* @return: all root-to-leaf paths
*/
vector<string> binaryTreePaths(TreeNode * root) {
vector<string> result;
if (!root) return result;
string path;
findPath(root, path, result);
return result;
}
private:
void findPath(TreeNode *root, string & path, vector<string> & result) {
if (root && !root->left && !root->right) {
result.push_back(path+to_string(root->val));
} else {
string tempStr=path + to_string(root->val) + "->";
if (root->left)
findPath(root->left, tempStr, result);
if (root->right)
findPath(root->right, tempStr, result);
}
}
};
注意:
- C++里面可以用to_string(int)来把一个int变成string。类似的方法还有springf(), stringstream, etc.
二刷:
class Solution {
public:
/**
* @param root: the root of the binary tree
* @return: all root-to-leaf paths
* we will sort your return value in output
*/
vector<string> binaryTreePaths(TreeNode *root) {
vector<string> res;
string str;
helper(root, res, str);
return res;
}
private:
void helper(TreeNode *root, vector<string> &res, string str) {
if (!root) return;
str = str + to_string(root->val);
if (!root->left && !root->right) {
res.push_back(str);
return;
}
str = str + "->";
helper(root->left, res, str);
helper(root->right, res, str);
return;
}
};
还有一个方法是用分治,九章参考答案如下,我感觉写的很好。下次再学习。
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<>();
if (root == null) {
return paths;
}
List<String> leftPaths = binaryTreePaths(root.left);
List<String> rightPaths = binaryTreePaths(root.right);
for (String path : leftPaths) {
paths.add(root.val + "->" + path);
}
for (String path : rightPaths) {
paths.add(root.val + "->" + path);
}
// root is a leaf
if (paths.size() == 0) {
paths.add("" + root.val);
}
return paths;
}