二叉树的相关算法

二叉树是一种层次存储的数据结构,其数据结构定义如下

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值