二叉树是一种层次存储的数据结构,其数据结构定义如下
struct TreeNode {
int val;
TreeNode* lchild; // 左孩子指针
TreeNode* rchild; // 右孩子指针
TreeNode(int val):val(val),lchild(nullptr),rchild(nullptr) {}
}
01,用非递归的方式求出二叉树的高度
int bfsdeepth(TreeNode* root) {
int res = 0;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
res++;
for (int i = 0; i < q.size(); ++i) {
TreeNode* curr = q.front();
q.pop();
if (curr->lchild) { q.push(curr->lchild); }
if (curr->lchild) { q.push(curr->rchild); }
}
}
return res;
}
02.试写出二叉树自上到下,自左到右的层序遍历算法
void showbfs(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
for (int i = 0; i < q.size(); ++i) {
TreeNode* curr = q.front();
q.pop();
cout << curr->val << " ";
if (curr->lchild) {q.push(curr->lchild);}
if (curr->rchild) {q.push(curr->rchild);}
}
}
}
TreeNode* swapTreeNodes(TreeNode* root) {
// 设树B是一颗采用链式存储结构的树,编写一个把树B中所有结点的左右子树进行交换的函数
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
for (int i = 0; i < q.size(); ++i) {
TreeNode* curr = q.front();
q.pop();
if (curr->lchild) { q.push(curr->lchild); }
if (curr->rchild) { q.push(curr->rchild); }
TreeNode* temp = curr->lchild;
curr->lchild = curr->rchild;
curr->rchild = temp;
}
}
return root;
}
设计一个算法,求先序遍历序列第k个结点的值
void getDesignateValue(TreeNode* root,int k) {
if (root == nullptr) {return;}
if (k == 1) {
cout << root->val << endl;
return;
}
k--;
getDesignateValue(root->left,k);
getDesignateValue(root->right,k):
}
设计一个算法,求二叉树的最大宽度
// 求二叉树的a最大宽度
int Maxwidth(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
int res = 0;
while (!q.empty()) {
int size = q.size();
res = max(res, size);
for (int i = 0; i < size; ++i) {
TreeNode* curr = q.front();
q.pop();
if (curr->lchild) { q.push(curr->lchild); }
if (curr->rchild) { q.push(curr->rchild); }
}
}
return res;
}
二叉树的带权路径长度(WPL)是二叉树中所有叶结点的带权路径长度之和,给定一颗二叉树T,请设计出求T的WPL算法
int WPL(TreeNode* root) {
if (root->left == nullptr && root->right == nullptr) {
return root->val;
}
return WPL(root->lchild) + WPL(root->rchild);
}