257. Binary Tree Paths
problem description
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
algorithm thought
就是将DFS的路线标记出来,最后返回。直接使用DFS做即可
只是这题需要注意一些细节,不然容易过不了一些测试样例
code
/**
* 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) {
vector<string> res;
if(root==nullptr)
return res;
string path=to_string(root->val);
if(root->left!=nullptr)
help(res,root->left,path);
path=to_string(root->val);
if(root->right!=nullptr)
help(res,root->right,path);
if(root->left==nullptr&&root->right==nullptr){
res.push_back(path);
}
return res;
}
void help(vector<string>&res,TreeNode* root,string&path){
int sz=path.size();
string number=to_string(root->val);
path+="->";path+=number;
if(root->left==nullptr&&root->right==nullptr){
res.push_back(path);
path.resize(sz);
return;
}
if(root->left!=nullptr)
help(res,root->left,path);
if(root->right!=nullptr)
help(res,root->right,path);
path.resize(sz);
}
};
algorithm analysis
DFS将树遍历一遍,时间复杂度O(n)。
Last updated