leetcode Binary Tree Paths

題目:

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%的通過率。
代碼:

/**
 * 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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章