首页 > 学院 > 开发设计 > 正文

LeetCode 257. Binary Tree Paths

2019-11-08 02:56:35
字体:
来源:转载
供稿:网友

题目链接:https://leetcode.com/PRoblems/binary-tree-paths/?tab=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"]思路:题目很简单,直接用DFS遍历保存路径即可

代码:

/** * 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> result;        string tmpPath="";        DFS(root,tmpPath,result);        return result;    }    void DFS(TreeNode* root,string path,vector<string> &Paths)    {        if(root==NULL)             return;        if(root->left==NULL&&root->right==NULL)        {            path+=to_string(root->val);            Paths.push_back(path);            return;        }        path+=to_string(root->val);        path+="->";        DFS(root->left,path,Paths);        DFS(root->right,path,Paths);    }};


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表