逐层打印二叉树

struct BinaryTreeNode {
    int nvalue=0;
    BinaryTreeNode* pleft = nullptr;
    BinaryTreeNode* pright = nullptr;
    BinaryTreeNode* parent = nullptr;
};
准备一个队列,通过不断的入队出队,逐层遍历二叉树的节点
vector<vector<int>> BinaryTreePrint(BinaryTreeNode* node) { vector<vector<int>> ans; if (node == nullptr) { throw exception("Invalid Input"); return ans; } queue<BinaryTreeNode*>q; q.push(node); while (!q.empty()) { int low = 0, high = q.size(); vector<int>v; while (low++ < high) { BinaryTreeNode* temp = q.front(); v.push_back(temp->nvalue); q.pop(); if (temp->pleft) { q.push(temp->pleft); } if (temp->pright) { q.push(temp->pright); } } ans.push_back(v); } return ans; }

 

posted @ 2020-07-18 18:22  卡冈图雅blackhole  阅读(147)  评论(0编辑  收藏  举报