Binary Tree Paths

来源:互联网 发布:seo推广 编辑:程序博客网 时间:2024/06/06 01:29

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

对树的深度优先搜索还是不熟悉,看了讨论区的答案。

定义了两个辅助函数。

string intToStr(int i)    {        stringstream ss;        ss<<i;        return ss.str();    }

简单的辅助函数,用来将int转换成sring。

void searchBT(TreeNode *root,string &path,vector<string> &ans)    {        if(!root->left && !root->right)            ans.push_back(path + intToStr(root->val));        if(root->left)        {            string s = path + intToStr(root->val)+"->";            searchBT(root->left,s,ans);        }        if(root->right)        {            string s = path + intToStr(root->val)+"->";             searchBT(root->right,s,ans);        }    }

主要的辅助函数。

如果当前的结点没有左右孩子,则直接将当前的path后追加当前结点的值后存入vector中。

如果当前的结点有左子树,则在当前path后追加当前结点的值后,对左子树调用该函数。

如果当前的结点有右子树,则在当前的path后追加当前结点的值后,对右子树调用该函数。

/** * 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> ret;                if(root)        {            string path="";            searchBT(root,path,ret);        }        return ret;                    }    private:    string intToStr(int i)    {        stringstream ss;        ss<<i;        return ss.str();    }    void searchBT(TreeNode *root,string &path,vector<string> &ans)    {        if(!root->left && !root->right)            ans.push_back(path + intToStr(root->val));        if(root->left)        {            string s = path + intToStr(root->val)+"->";            searchBT(root->left,s,ans);        }        if(root->right)        {            string s = path + intToStr(root->val)+"->";             searchBT(root->right,s,ans);        }    }};



0 0
原创粉丝点击