[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:
All root-to-leaf paths are:
思路:
这也是一道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);
}
}
};
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);
}
}
};
相关文章推荐
- 【LeetCode】257. Binary Tree Paths 解题报告
- LeetCode解题报告 257. Binary Tree Paths [easy]
- [leetcode] 257. Binary Tree Paths 解题报告
- LeetCode 257. Binary Tree Paths 解题报告
- LeetCode(254) Binary Tree Paths解题报告
- LeetCode-Binary Tree Paths -解题报告
- 【LeetCode】Binary Tree Paths 解题报告(java & python)
- Leetcode 104. Maximum Depth of Binary Tree 二叉树的最大高度 解题报告
- LeetCode 104.Maximum Depth of Binary Tree 解题报告
- [leetcode] 261. Graph Valid Tree 解题报告
- LeetCode 257. Binary Tree Paths (二叉树路径)
- 【LeetCode】Minimum Depth of Binary Tree 解题报告
- leetcode 257. Binary Tree Paths---java
- 【LeetCode】226. Invert Binary Tree 解题报告
- 【LeetCode】Diameter of Binary Tree 解题报告
- 【LeetCode】111.Minimum Depth of Binary Tree(Easy)解题报告
- 【LeetCode】100.Same Tree(Easy)解题报告
- [leetcode] 111. Minimum Depth of Binary Tree 解题报告
- [Leetcode] 110. Balanced Binary Tree 解题报告
- [leetcode] 110. Balanced Binary Tree 解题报告