[LeetCode]Binary Tree Paths

来源:互联网 发布:linux中cd的用法 编辑:程序博客网 时间:2024/06/08 08:20

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> ret;        string temp ;        traversal(ret,temp,root);        return ret;    }    void traversal(vector<string> &ret,string temp,TreeNode *root){        if(root==nullptr)            return ;        temp +=  ("->"+ to_string(root->val));        traversal(ret,temp,root->left);        traversal(ret,temp,root->right);        if(root->left==nullptr&&root->right==nullptr) ret.push_back(temp.substr(2));    }};


0 0