zoukankan      html  css  js  c++  java
  • Binary Tree Paths

    Description:

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

    Code:

      void allPath(TreeNode*root, vector<string>&result, vector<int>&path)
        {
            if (root==NULL)
                return ;
            path.push_back(root->val);
            if (root->left==NULL && root->right==NULL)
            {
    //注意这里要用ostringstream将字符串写到流中去,然后用str()函数返回字符串
                ostringstream sstr;
                for (int i = 0; i < path.size()-1; ++i)
                    sstr << path[i]<<"->";
                sstr<<path[path.size()-1];
                result.push_back(sstr.str());
            }
            else
            {
                if (root->left)
                    allPath(root->left, result, path);
                if (root->right)
                    allPath(root->right, result, path);
            }
            path.pop_back();
        }
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string>result;
            vector<int>path;
            allPath(root, result,path);
            return result;
        }
  • 相关阅读:
    P3275 [SCOI2011]糖果 题解
    hdu 2962 题解
    hdu 2167 题解
    hdu 2476 题解
    hdu 5418 题解
    2019.10.16&17小结
    poj 3061 题解(尺取法|二分
    poj 1852&3684 题解
    NOIP2017[提高组] 宝藏 题解
    一类经典问题的解法
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4752028.html
Copyright © 2011-2022 走看看