LeetCode 257. Binary Tree Paths(二叉树根到叶子的全部路径)

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: 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;
        
        binaryTreePaths(res, root, to_string(root->val));
        
        return res;
    }
    
    void binaryTreePaths(vector<string>& res, TreeNode* root, string t)
    {
        if (!root->left && !root->right)
        {
            res.push_back(t);
            return;
        }
        
        if (root->left) binaryTreePaths(res, root->left, t + "->" + to_string(root->left->val));
        if (root->right) binaryTreePaths(res, root->right, t + "->" + to_string(root->right->val));
    }
    
};

 

posted @ 2019-06-05 15:20  douzujun  阅读(307)  评论(0编辑  收藏  举报