您的位置:首页 > 其它

[Leetcode] 257. Binary Tree Paths 解题报告

2017-07-04 09:54 597 查看
题目

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

思路

这也是一道DFS的题目,关键是要判断出来一个结点是不是叶子结点。

代码

/**
* 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 {};
}
vector<string> ret;
string line;
binaryTreePaths(root, ret, line);
return ret;
}
private:
void binaryTreePaths(TreeNode* root, vector<string>& ret, string line) {
if(line.size() > 0) {
line += "->";
}
line += to_string(root->val);
if(root->left == NULL && root->right == NULL) {
ret.push_back(line);
return;
}
if(root->left) {
binaryTreePaths(root->left, ret, line);
}
if(root->right) {
binaryTreePaths(root->right, ret, line);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: