Saturday, August 15, 2015

[LeetCode] Binary Tree Paths

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> res;
        if(!root) return res;
        string cur = to_string(root->val);
        if(root->left) 
        {
            vector<string> left = binaryTreePaths(root->left);
            for(auto e: left)
            {
                res.push_back(cur + "->" + e);
            }
        }
        if (root->right)
        {
            vector<string> right = binaryTreePaths(root->right);
            for(auto e: right)
            {
                res.push_back(cur + "->" + e);
            }            
        }
        
        if(!root->right && !root->left)
        {
            res.push_back(to_string(root->val));
        }
        return res;
    }
};