您的位置:首页 > 其它

Binary Tree Paths

2015-08-16 14:14 260 查看
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"]

思路很简单:大概就是先序遍历。

/**
* 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> path;
vector<string> finalResult;
deepTravel(root,path,finalResult);
return finalResult;
}

void deepTravel(TreeNode* root,vector<string>& tempPaths,vector<string>& finalResult)
{
//判断当前结点是否为空
if(root == NULL)
return;
//当前结点不为空就把当前结点的值转换为字符串。然后压入路径vector中
string temp;
stringstream ss;
ss<<root->val;
ss>>temp;
if(tempPaths.size()!=0)//如果前面已经有结点了,就添加箭头。
tempPaths.push_back("->");
tempPaths.push_back(temp);

//如果当前结点没有左右子树,就将tempPath中的结点组合成一整个路径字符串。然后压入finalResult中
if(root->left == NULL && root->right==NULL)
{
string temp;
for(vector<string>::iterator iter = tempPaths.begin(); iter!=tempPaths.end();iter++)
{
temp+=*iter;
}
finalResult.push_back(temp);
return;
}
//如果当前结点有左右子树,就递归下去遍历
if(root->left != NULL)
{
deepTravel(root->left,tempPaths,finalResult);
//先把左子树的结果弹出
tempPaths.pop_back();
tempPaths.pop_back();

}
//如果当前结点有左右子树,就递归下去遍历
if(root->right != NULL)
{
deepTravel(root->right,tempPaths,finalResult);
tempPaths.pop_back();
tempPaths.pop_back();
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: