leetcode 257:Binary Tree Paths

来源:互联网 发布:大数据的弱点有哪些 编辑:程序博客网 时间:2024/05/16 08:12

问题描述:

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

思路:

这又是一道遍历二叉树的题目,谨记叶节点的定义,做出操作判断。

这次我给类Solution增加一个私有成员result用来记录字符串数组,因为我想增加一个能递归调用的函数,然后里面也能够保存root-to-leaf路径,所以只能通过增加成员来实现了。

思路是深度优先遍历,每读取一个节点,就将其数值接到传入的字符串str后面,然后将str作为参数传入到儿子节点的读取中去。一旦遇到叶子节点,就将str添加到result数组。

前面稍微处理一下root节点,后面的问题就可以递归完成。

代码:

class Solution {private:    vector<string> result;public:    vector<string> binaryTreePaths(TreeNode* root) {        if (root == NULL) return result;        string str = "";        stringstream ss;        string transf;        ss << root->val;        ss >> transf;        str = str + transf;        if (root->left == NULL && root->right == NULL)        {            result.push_back(str);        }        if (root->left)     readVal(root->left, str);        if (root->right)    readVal(root->right, str);        return result;    }    void readVal(TreeNode *root, string str)    {        stringstream ss;        string transf;        ss << root->val;        ss >> transf;        str = str + "->" + transf;        //deal with the leaf node        if (root->left == NULL && root->right == NULL)          {            result.push_back(str);        }        if (root->left)     readVal(root->left, str);        if (root->right)    readVal(root->right, str);    }};
0 0
原创粉丝点击