创建/输出二叉树(不是BST)

时间:2016-11-09 23:46:40

标签: c++ dictionary binary-tree

我的代码(下面)有效,除非所需的密钥尚未在列表中(因此,如果某个节点没有对其父级的引用)。它会忽略节点,只是在没有它们的情况下创建一个树。我该如何解决?我正在考虑在所有键都进入后重新循环,并继续相应地添加和删除。

#include <iostream>
#include <string>
#include <sstream>
#include <memory>
#include <map>

struct Foo {
  int data{0};
  int left{-1};
  int right{-1};
};

std::istream& operator>>(std::istream& in, Foo& ff) {
  in >> ff.data >> ff.left >> ff.right;
  return in;
}

struct Del {
  template <class T>
  void operator()(T* p) {
    std::cout << "[deleted #" << (p ? p->data : 0) << "]\n";
    delete p;
  }
};

struct Bar {
  int data{0};
  std::unique_ptr<Bar, Del> lef;
  std::unique_ptr<Bar, Del> rig;
};

void print(const std::unique_ptr<Bar, Del>& node) {
  if (node) {
    std::cout << ' ' << node->data;
    print(node->lef);

    print(node->rig);
  }
}

int main() {
  std::string input =
      "101 1 3 102 2 8 104 6 7 103 -1 5 109 -1 -1 106 4 -1 107 -1   -1 108 -1 "
      "-1 105 -1 -1";

  std::istringstream IN(input);

  std::map<int, std::pair<Bar*, bool>> mlist;
  std::unique_ptr<Bar, Del> root;
  int row = 0;
  Foo entry;
  while (IN >> entry) {
    if (0 == row) {
      root.reset(new Bar);
      Bar* node = root.get();
      node->data = entry.data;
      std::cout << row << " [created #" << entry.data << ']';
      if (0 <= entry.left)
        mlist.emplace(entry.left, std::make_pair(node, true));
      if (0 <= entry.right)
        mlist.emplace(entry.right, std::make_pair(node, false));

    } else {
      auto it = mlist.find(row);
      if (mlist.end() != it) {
        if (it->second.second) {
          it->second.first->lef.reset(new Bar);
          Bar* node = it->second.first->lef.get();
          node->data = entry.data;
          std::cout << row << " [created #" << entry.data << ']';
          if (0 <= entry.left)
            mlist.emplace(entry.left, std::make_pair(node, true));
          if (0 <= entry.right)
            mlist.emplace(entry.right, std::make_pair(node, false));

          mlist.erase(it);
        } else {
          it->second.first->rig.reset(new Bar);
          Bar* node = it->second.first->rig.get();
          node->data = entry.data;
          std::cout << row << " [created #" << entry.data << ']';
          if (0 <= entry.left)
            mlist.emplace(entry.left, std::make_pair(node, true));
          if (0 <= entry.right)
            mlist.emplace(entry.right, std::make_pair(node, false));

          mlist.erase(it);
        }
        // mlist.erase( it );
      }
    }
    std::cout << " list size " << mlist.size() << '\n';
    ++row;
  }
  std::cout << "final list size " << mlist.size() << "\n\n";
  print(root);
  std::cout << "\n\n";
  std::cout << "Lets see whats left in the list:";

  return 0;
}

1 个答案:

答案 0 :(得分:0)

实际上,我只使用了一个节点向量,它运行得很好。抱歉所有的困惑!