LeetCode 257. Binary Tree Paths

来源:互联网 发布:vb语言基本代码 编辑:程序博客网 时间:2024/06/07 03:14

257. Binary Tree Paths

Description
Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:
这里写图片描述
All root-to-leaf paths are:

[“1->2->5”, “1->3”]

Analysis
这道题的求出所有从根到叶子节点的理。
我的做法是先记录路径,然后当每一次路径都走到叶子节点的时候,就将该路径记录到向量中,最后得到答案。

Code

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //find one path and then push backclass Solution {public:    void fun(TreeNode* root,string path,vector<string>&res){        if(root->left==NULL&&root->right==NULL){            res.push_back(path);            return ;        }        if(root->left) fun(root->left,path+"->"+to_string(root->left->val),res);        if(root->right) fun(root->right,path+"->"+to_string(root->right->val),res);    }    vector<string> binaryTreePaths(TreeNode* root) {        vector<string> res;        if(root == NULL) return res;        string path = to_string(root->val);        fun(root,path,res);        return res;    }};
0 0
原创粉丝点击