0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Tree構造を表現したクラス

Last updated at Posted at 2019-03-20

お題

  • ["親id","子id","孫id","ひ孫id",...] という可変長のidの組み合わせが複数インプットされる。
  • 親のidに子のidが結びつくようにする。同じ親idの子が複数あれば、子は同じ親に結びつくようにする。

例えば、入力が、 [1,2,3] [1,4] [5,6] [1,2,7] である場合、以下のツリー構造となるように。

1--2--3
 |  `-7
 `-4
5--6

解答例

CNode.h
class CNode {
public:
    /**
     * 指定された id の Node を作る。
     */
    CNode(
        const char *id);

    virtual ~CNode();

    /**
     * Node の id を返す。
     */
    ::std::string getID();

    /**
     * 指定した childID の子Nodeが存在しなければ、子Nodeを作成し子Nodeを返す。
     * 指定した childID の子Nodeが存在していれば、既に存在する子Nodeを返す。
     */
    CNode *createChildIfNotExist(
        const char *childID);

    /**
     * 子Node の一覧を返す。
     */
    const ::std::vector<CNode *> &getChildren();

private:
    ::std::string fID;
    ::std::vector<CNode *> fChildren;
};
main.cpp
    CNode *root = new CNode("root");
    for (int i = 0; i < kNumOfIDs; i++) {
        ::std::vector< ::std::string > ids = split(kIDs[i]); // idsの要素はid "1" とか "2" とか。
        CNode *cur = root;
        for (::std::vector< ::std::string >::const_iterator itr = ids.begin(); itr != ids.end(); itr++) {
            cur = cur->createChildIfNotExist(itr->c_str());
        }
    }

入力と結果

static const char *const kIDs[] = 
{"4,3,6"
,"2,7"
,"0,1"
,"2,5"
,"0,8"
};
 $ ./a.out 
 root
   4
      3
         6
   2
      7
      5
   0
      1
      8
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?