• 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;
        }
  • 相关阅读:
    http返回码
    WCF 超时
    MVC异步
    熔断设计模式
    JAVA学习图
    java io模型
    keep alive 长连接
    Java异常处理 误区
    架构的本质
    Repository模式
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4752028.html
Copyright © 2020-2023  润新知