257. Binary Tree Paths

2018/04/30 leetcode 共 601 字,约 2 分钟

Title

the problem link

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

Solution

//cpp:
   vector<string> binaryTreePaths(TreeNode* root) {     
        vector<string>ans; 
        string item;
        dfs(root, item, ans);
        return ans;
    }
    
    void dfs(TreeNode* root, string& item, vector<string>& ans ){
         if(!root)  return;
        string before=item;
        item+=to_string(root->val)+"->";
        if(!root->left&&!root->right){
             item.erase(item.end()-2,item.end());          
            ans.push_back(item); 
           }
         dfs(root->left, item, ans);
         dfs(root->right, item, ans);
        item=before;
    }

Search

    Table of Contents