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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章