LeetCode_binary-tree-paths

来源:互联网 发布:兵马俑知乎 编辑:程序博客网 时间:2024/05/23 12:14

原题链接:https://leetcode.com/problems/binary-tree-paths/

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */      /*    int i = 1000;        stream << i; //将int输入流        stream >> result; //从stream中抽取前面插入的int值*/        //对递归的理解:1)不需要知道具体的细节,只需要知道其过程就行了;2)递归的调用实际上就是函数的调用,不要怕,一定能掌握class Solution {public:    vector<string> binaryTreePaths(TreeNode* root)    {                string str="";        vector<string> path;       if(!root)            return path;        searchPaths(path,str,root);        return path;    }    void searchPaths(vector<string> &path,string str,TreeNode* root)    {        stringstream stream;        if(!root->left && !root->right)//叶子节点        {            stream << root->val;            //stream >> str;            str += stream.str();//不理解为什么要+=而不是直接=            path.push_back(str);            return;        }        else//非叶子节点        {            stream << root->val;            //stream >> str;            str += stream.str() + "->";</span><span style="font-size:18px;">//不理解为什么要+=而不是直接=,待重新回头考虑,需要对stringstream做一定的理解            //path.push_back(str);            if(root->left)                searchPaths(path,str,root->left);            if(root->right)                searchPaths(path,str,root->right);        }    }};//思路:从根节点出发,往左边走,如果当前结点不是叶子节点则当前值+“->”,否则记录当前值;递归结束条件是叶子节点则返回。


0 0
原创粉丝点击