題目:二叉樹的層次遍歷
層序遍歷就是按二叉樹從上到下,從左到右依次打印每個節點中存儲的數據。
思路標籤:
- 數據結構:隊列
解答:
- 二叉樹的層次遍歷滿足隊列先入先出的規則;
- 每次訪問隊列頭部節點,將其出隊列,並將其左右子節點分別入隊列。
struct BinaryTree {
int val;
BinaryTree *left;
BinaryTree *right;
BinaryTree(int value)
: val(value), left(nullptr), right(nullptr) { }
};
void levelOrder(BinaryTree *root) {
if (root == nullptr)
return;
queue<BinaryTree*> que;
que.push(root);
while (!que.empty()) {
BinaryTree *front = que.front();
cout << front->val << " ";
que.pop();
if (front->left != nullptr)
que.push(front->left);
if (front->right != nullptr)
que.push(front->right);
}
}
題目:二叉樹的深度(層次遍歷)
利用層次遍歷可以得到二叉樹的深度
思路標籤:
- 數據結構:隊列
解答:
- 二叉樹的層次遍歷滿足隊列先入先出的規則;
- 每次訪問隊列頭部節點,將其出隊列,並將其左右子節點分別入隊列。
struct BinaryTree {
int val;
BinaryTree *left;
BinaryTree *right;
BinaryTree(int value)
: val(value), left(nullptr), right(nullptr) { }
};
int treeDepth(BinaryTree* root) {
if (root == nullptr) return 0;
int depth = 0;
queue<BinaryTree*> que;
que.push(root);
while (!que.empty()) {
depth++;
int count = 0;
int size = que.size();
while (count < size) { //彈出當前層的所有節點
BinaryTree *front = que.front();
que.pop();
count++;
if (front->left)
que.push(front->left);
if (front->right)
que.push(front->right);
}
}
return depth;
}