逐层打印二叉树

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; }

 

上一篇:Java二叉树


下一篇:【C++】二叉树代码汇总(构建+遍历+求深度+求结点数)