逐层打印二叉树

struct BinaryTreeNode {
    int nvalue=0;
    BinaryTreeNode* pleft = nullptr;
    BinaryTreeNode* pright = nullptr;
    BinaryTreeNode* parent = nullptr;
};
准备一个队列,通过不断的入队出队,逐层遍历二叉树的节点
vectorint>> BinaryTreePrint(BinaryTreeNode* node) { vectorint>> ans; if (node == nullptr) { throw exception("Invalid Input"); return ans; } queueq; 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; }

 

你可能感兴趣的:(逐层打印二叉树)