889. 根据前序和后序遍历构造二叉树;114. 二叉树展开为链表

返回与给定的前序和后序遍历匹配的任何二叉树。

 pre 和 post 遍历中的值是不同的正整数。

 

示例:

输入:pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
输出:[1,2,3,4,5,6,7]


 

提示:


    1 <= pre.length == post.length <= 30
    pre[] 和 post[] 都是 1, 2, ..., pre.length 的排列
    每个输入保证至少有一个答案。如果有多个答案,可以返回其中一个。

class Solution {
public:
    TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
        if(pre.size()==0)return nullptr;
        return buildTree(pre,0,pre.size()-1,post,0,post.size()-1);
    }
    TreeNode *buildTree(vector<int> &pre,int a,int b,vector<int> &post,int c,int d){
        if(a>b)return nullptr;
        TreeNode *cur=new TreeNode(pre[a]);
        if(a==b)return cur;
        int pos=0;
        for(;post[pos]!=pre[a+1];++pos);//改进:可以把post元素放到map里快速查找
        int diff=pos-c;
        auto left=buildTree(pre,a+1,a+1+diff,post,c,pos);
        auto right=buildTree(pre,a+2+diff,b,post,pos+1,d-1);
        cur->left=left;
        cur->right=right;
        return cur;
    }
};

给定一个二叉树,原地将它展开为一个单链表。

 

例如,给定二叉树

    1
   / \
  2   5
 / \   \
3   4   6

将其展开为:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

class Solution {
public:
    void flatten(TreeNode* root) {
        helper(root);
    }
    TreeNode *helper(TreeNode *cur){
        if(!cur)return nullptr;
        if(!cur->left&&!cur->right)return cur;
        if(!cur->left)return helper(cur->right);
        auto temp=helper(cur->left);
        temp->right=cur->right;
        cur->right=cur->left;
        cur->left=nullptr;
        return helper(temp);
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值