[257]Binary Tree Paths

来源:互联网 发布:今日特惠淘宝优站 编辑:程序博客网 时间:2024/05/16 05:21

【题目描述】

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

【思路】

递归深搜。

【代码】

/** * 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> binaryTreePaths(TreeNode* root) {        vector<string> vec;        string str="";        if(root==NULL) return {};        path(root,vec,str);        return vec;    }    void path(TreeNode* root,vector<string> &vec,string str){        if(root==NULL) return;        if(str=="") str=str+to_string(root->val);        else str=str+"->"+to_string(root->val);        if(root->left==NULL&&root->right==NULL){            vec.push_back(str);            return;        }        if(root->left!=NULL){           path(root->left,vec,str);          }       if(root->right!=NULL){           path(root->right,vec,str);          }    }};


0 0
原创粉丝点击