您的位置:首页 > 其它

leetcode Binary Tree Paths

2015-12-11 21:01 197 查看
题目:

[code]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保存到vector < string> 里面。只是对树的递归遍历,但是令人吃惊的是这道题在leetcode上只有 24%的通过率。

代码:

[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> res ;
    void getPath(TreeNode* root,string s)
    {
        if(root->right == NULL && root->left == NULL)
           res.push_back(s);
        if(root->left!=NULL)
        {
             string s1 ;
             s1 = s + "->" + int2string(root->left->val);
            cout << s1 << endl;

             getPath(root->left,s1);
        }
        if(root->right!=NULL)
        {
             string s1 ;
             s1 = s + "->" + int2string(root->right->val);
             cout << s1 << endl;
             getPath(root->right,s1);
        }
    }
    string int2string(int Number)
    {
        string Result;

        stringstream convert; 

        convert << Number;
        Result = convert.str();
        return Result;
    }

    vector<string> binaryTreePaths(TreeNode* root) {
        string s;
        if(root != NULL)
        {
            s = to_string(root->val);
            getPath(root,s);
        }
        cout << "out if " << endl;
        return res;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: