根据前序遍历和后序遍历构造二叉树(Construct Binary Tree from Preorder and Postorder Traversal)

889. Construct Binary Tree from Preorder and Postorder Traversal

来源: LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal

题目描述

889. Construct Binary Tree from Preorder and Postorder Traversal
Return any binary tree that matches the given preorder and postorder traversals.

Values in the traversals pre and post are distinct positive integers.

 

Example 1:

Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]
 

Note:

1 <= pre.length == post.length <= 30
pre[] and post[] are both permutations of 1, 2, ..., pre.length.
It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.

思路分析

利用前后序序列创建父与子的集合
前序遍历后面的一位一定为左儿子,后序遍历前面的一位一定为右儿子
一趟循环,保存其每个结点的儿子情况
根据根节点的值搜索
左儿子 = 右二子 (多解) 这里都假设为此时为左儿子
不等时建立
递归求解
设置结点使用数组和以判断的节点数提前结束

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
# define REP(i, a) for(int i = 0; i < (a); ++i)
# define FOR(i, a, b) for(int i = (a); i<(b); ++i)
int a1[31];
int a2[31];
vector<bool> use;
int cnt;
public:
    
    TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
        // pre and post construct binary tree
        memset(a1, 0, 31*sizeof(int));
        memset(a2, 0, 31*sizeof(int));
        use.resize(pre.size()+1, false);
        REP(i, pre.size() - 1) a1[pre[i]] = pre[i+1];// pre[i] ->left-> pre[i+1] 
        for(int i = post.size() - 1; i>0; --i) a2[post[i]] = post[i - 1]; // post[i] ->right ->post[i-1]
        TreeNode* root = new TreeNode(pre[0]); // 根节点
        cnt = pre.size() - 1; use[pre[0]] = true;
        recur(root, pre[0]);
        return root;
    }
    void recur(TreeNode* root, int val){
        if(cnt == 0) return;
        if(!use[a1[val]] && a1[val] == a2[val]) {
            --cnt; use[a1[val]] = true;
            root->left = new TreeNode(a1[val]);
            recur(root->left, a1[val]);
        }
        else if(!use[a1[val]]){
            cnt -= 2; use[a1[val]] = true; use[a2[val]] = true;
            root->left = new TreeNode(a1[val]);
            root->right = new TreeNode(a2[val]);
            recur(root->left, a1[val]);
            recur(root->right, a2[val]);
        }
    }
};

你可能感兴趣的:(LeetCode总结,#,Tree)