题目:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
All root-to-leaf paths are:
[“1->2->5”, “1->3”]
这一题是最基础的深搜题,要我们列出一棵二叉树从根到所有叶子的路径。用递归来实现非常简单,但要注意解的格式(每个结点的值直接要用‘->’隔开,而且每个结点的值可能是负数)。时间复杂度为O(2^(n-1))。Accepted的代码:
/**
* 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:
void dfs(TreeNode* p,vector<string>& result,string s)
{
//考虑值为负的情况
if(p->val<0)
{
s+='-';
p->val=p->val*(-1);
}
//考虑值不止一位数的情况
stack<char> temp;
while(p->val!=0)
{
temp.push(p->val%10+'0');
p->val=p->val/10;
}
while(!temp.empty())
{
s=s+temp.top();
temp.pop();
}
if(p->left==NULL&&p->right==NULL) result.push_back(s);//终止条件
else
{
s=s+'-';
s=s+'>';
if(p->left!=NULL) dfs(p->left,result,s);
if(p->right!=NULL) dfs(p->right,result,s);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
if(root==NULL) return result;
string s="";
dfs(root,result,s);
return result;
}
};