刷题常用的二叉树代码模板

二叉树结点定义

struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode() : val(0), left(nullptr), right(nullptr) {}
      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

二叉树的构造

层序序列构造

  • 输入完全二叉树的序列,空结点位置用特殊字符标记,输出构造好的二叉树。
  • 基于队列 + bfs即可。

前序序列和中序序列构造

	//函数定义:根据前序序列preorder[preStart, preEnd] 和 中序序列inorder[inStart, inEnd]来构造对应的二叉树并返回根结点
    TreeNode* build(vector<int>& preorder, int preStart, int preEnd, vector<int>& inorder, int inStart, int inEnd){
        if(preStart > preEnd || inStart > inEnd) return nullptr;//区间非法
        int rootVal = preorder[preStart];//根节点就是前序序列的首元素
        int index = 0;
        for(int i = inStart; i <= inEnd; i++){//获取根节点在中序序列中的位置
            if(inorder[i] == rootVal){
                index = i;
                break;
            }
        }
        int leftSize = index - inStart;
        //构造根节点
        TreeNode *root = new TreeNode(rootVal);
        //基于区间划分递归构造左子树和右子树
        root->left = build(preorder, preStart + 1,preStart + leftSize, inorder, inStart, index - 1);
        root->right = build(preorder, preStart + leftSize + 1, preEnd, inorder, index + 1, inEnd);
        return root;
    }

后序序列和中序序列构造

	TreeNode *build(vector<int>& inorder,int inStart,int inEnd, vector<int>& postorder,int postStart,int postEnd){
        if(inStart>inEnd || postStart>postEnd)
            return nullptr;
        int rootVal = postorder[postEnd];
        int index = 0;
        for(int i = inStart;i <= inEnd;i++){
            if(inorder[i] == rootVal)
                index = i;
        }
        int leftSize = index - inStart;
        TreeNode *root = new TreeNode(rootVal);
        root->left = build(inorder,inStart,index - 1,postorder,postStart,postStart + leftSize -1);
        root->right = build(inorder,index + 1,inEnd,postorder,postStart + leftSize,postEnd - 1);
        return root;
    }

序列化和反序列化

层序序列化和反序列化

前序序列化和反序列化

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值