letecode [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

Subject to the effect :

  Given binary tree, all of its output paths, with the vector storage container.

Understanding:

  Using recursive thinking.

  Root node, if it is empty, the empty container is returned. If the root node is a leaf node, the instructions to locate the end of the path, the path is added to the container.

  For the root node, recursively obtain its left and right subtrees path, then the root node added value, added to the vessel.

Code C ++:

/**
 * 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;
        string str;
        if(root==NULL)
            return res;
        str = to_string(root->val);
        if(root->left==NULL && root->right==NULL){
            res.push_back(str);
            return res;
        }
        str += "->";
        string res_str;
        vector<string> leftRes,rightRes;
        leftRes = binaryTreePaths(root->left);
        for(int i=0;i<leftRes.size();++i){
            res_str = str + leftRes[i];
            res.push_back(res_str);
        }
        rightRes = binaryTreePaths(root->right);
        for(int i=0;i<rightRes.size();++i){
            res_str = str + rightRes[i];
            res.push_back(res_str);
        }
        return res;
    }
};

operation result:

  When execution: 12 ms, beat the 78.14% of all users to submit in C ++

  Memory consumption: 12.1 MB, defeated 72.05% of all users to submit in C ++

Guess you like

Origin www.cnblogs.com/lpomeloz/p/11024545.html