Binary Tree Paths

来源:互联网 发布:百度云域名查询 编辑:程序博客网 时间:2024/04/30 13:47

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

第一个错误版本class Solution {public:    vector<string> binaryTreePaths(TreeNode* root) {        if(!root) return{};        vector<string> v;        string s("");        binaryTreePaths(v,s,root);        return v;    }    void binaryTreePaths(vector<string> &v,string s,TreeNode *root){        if(!root) return;        string s1=root->val+"";       if(s!="") s1=s+"->"+s1;         if(!root->right||!root->left) v.push_back(s1);       if(root->left) binaryTreePaths(v,s1,root->left);       if(root->right) binaryTreePaths(v,s1,root->right);    }};

这里错误原因在于对树的路径没有理解透彻,比如
1
/ \
2 3
\
5
正确的路径应该是如下:

[“1->2->5”, “1->3”]
而按照我之前的思路,路径就变成了
[“1->2”,”1->2->5”, “1->3”,]
路径是根到叶子的路径。而叶子是指既没有左孩子也没有右孩子,所以节点”2“不是叶子,所以”1->2”不是路径

正确的答案

class Solution {public:    vector<string> binaryTreePaths(TreeNode* root) {        if(!root) return{};        vector<string> v;      //  string s("");        binaryTreePaths(v,to_string(root->val),root);        return v;    }    void binaryTreePaths(vector<string> &v,string s,TreeNode *root){        if(!root) return;       // string s1=root->val+"";      // if(s!="") s1=s+"->"+s1;         if(!root->right&&!root->left) {v.push_back(s);return;}       if(root->left) binaryTreePaths(v,s+"->"+to_string(root->left->val),root->left);       if(root->right) binaryTreePaths(v,s+"->"+to_string(root->right->val),root->right);    }};

int转化为string的两种方法:
1.string s=root->val+””
2.to_string(root->val)

0 0