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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值