MDGSF Software Engineer

[算法学习][leetcode] 257 Binary Tree Paths

2017-09-05
mdgsf
Art

https://leetcode.com/problems/binary-tree-paths/description/

题目

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

Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

题目翻译

题目解析

参考答案

#include <iostream>
#include <vector>
#include <string>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

/**
* 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:

    void Traverse(TreeNode * root, vector<int> & vecPathValue, vector<string> & result)
    {
        if (NULL == root)
        {
            return;
        }

        vecPathValue.push_back(root->val);
        if (root->left == NULL && root->right == NULL)
        {
            string str;
            for (int i = 0; i < vecPathValue.size(); i++)
            {
                if (i == 0)
                {
                    char acTemp[128] = { 0 };
                    sprintf(acTemp, "%d", vecPathValue[i]);
                    str = str + string(acTemp);
                }
                else
                {
                    char acTemp[128] = { 0 };
                    sprintf(acTemp, "->%d", vecPathValue[i]);
                    str = str + string(acTemp);
                }
            }
            result.push_back(str);
        }
        else
        {
            Traverse(root->left, vecPathValue, result);
            Traverse(root->right, vecPathValue, result);
        }
        vecPathValue.pop_back();
    }

    vector<string> binaryTreePaths(TreeNode* root)
    {
        vector<int> vecPathValue;
        vector<string> result;
        Traverse(root, vecPathValue, result);
        return result;
    }
};

int main()
{
    return 0;
}

weixingongzhonghao

Similar Posts

Comments