LeetCode 105, 106. Construct Binary Tree from Preorder and Inorder/Inorder and Postorder Traversal

1. 题目描述

105 Given preorder and inorder traversal of a tree, construct the binary tree.
106 Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

2. 解题思路

这个题目很常规, 还是使用递归的思路进行处理, 先根据先序或者后序确定中间节点的值, 然后在中序中找到相应节点, 前半部分为左子树, 后半部分为右子树, 递归调用就可以了

3. code

3.1 105

class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return buildTree(preorder, 0, preorder.size(), inorder, 0, inorder.size());
    }

private:
    TreeNode * buildTree(vector<int>& preorder, int prestart, int prestop,
        vector<int>& inorder, int instart, int instop){
        if (prestart >= prestop || instart >= instop)
            return nullptr;

        TreeNode * root = new TreeNode(preorder[prestart]);
        auto iter = find(inorder.begin() + instart, inorder.begin() + instop, preorder[prestart]);
        int pos = iter - inorder.begin();
        TreeNode * left = buildTree(preorder, prestart + 1, prestart + 1 + pos - instart,
            inorder, instart, pos);
        TreeNode * right = buildTree(preorder, prestart + 1 + pos - instart, prestop,
            inorder, pos + 1, instop);
        root->left = left;
        root->right = right;
        return root;
    }
};

3.2 106

class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return buildTree(inorder, 0, inorder.size(), postorder, 0, postorder.size());
    }

private:
    TreeNode* buildTree(vector<int>& inorder, int instart, int instop,
        vector<int>& postorder, int poststart, int poststop){
        if (instart >= instop || poststart >= poststop)
            return nullptr;

        int data = postorder[poststop - 1];
        TreeNode * root = new TreeNode(data);
        auto iter = find(inorder.begin() + instart, inorder.begin() + instop, data);
        int pos = iter - inorder.begin();
        TreeNode * left = buildTree(inorder, instart, pos,
            postorder, poststart, poststart + pos - instart);
        TreeNode * right = buildTree(inorder, pos + 1, instop,
            postorder, poststart + pos - instart, poststop - 1);
        root->left = left;
        root->right = right;
        return root;
    }
};

4. 大神代码

// 105 迭代的处理方式, 虽然没怎么看明白
/*
The idea is as follows:

1) Keep pushing the nodes from the preorder into a stack (and keep making the tree by adding nodes to the left of the previous node) until the top of the stack matches the inorder.

2) At this point, pop the top of the stack until the top does not equal inorder (keep a flag to note that you have made a pop).

3) Repeat 1 and 2 until preorder is empty. The key point is that whenever the flag is set, insert a node to the right and reset the flag.
*/
class Solution {
public:
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        if (preorder.size() == 0) return NULL;
        int ppre = 0, pin = 0;
        TreeNode *root = new TreeNode(preorder.at(ppre++));
        TreeNode *p = NULL;
        stack<TreeNode *> roots;
        roots.push(root);

        while (true) {
            if (inorder.at(pin) == roots.top()->val) {
                p = roots.top();
                roots.pop();
                pin++;
                if (pin == inorder.size()) break;
                if (roots.size() && inorder.at(pin) == roots.top()->val) continue;
                p->right = new TreeNode(preorder.at(ppre));
                ppre++;
                roots.push(p->right);
            }
            else {
                p = new TreeNode(preorder.at(ppre));
                ppre++;
                roots.top()->left = p;
                roots.push(p);
            }
        }

        return root;
    }
};
// 106
/*
Below is the O(n) solution from @hongzhi but that discuss is closed now 'cause @hongzhi says little about his code.

https://oj.leetcode.com/discuss/6334/here-is-my-o-n-solution-is-it-neat

I've modified some of and tried this code and got AC. Just share about some comprehension about his code.

I've modified vtn(vector) to stn(stack) in that stack is probably what this algs means and needs.

What matters most is the meaning of stn.

Only nodes whoes left side hasn't been handled will be pushed into stn.

And inorder is organized as (inorder of left) root (inorder of right),

And postorder is as (postorder of left) (postorder of right) root.

So at the very begin, we only have root in stn and we check if inorder.back() == root->val and in most cases it's false(see Note 1). Then we make this node root's right sub-node and push it into stn.

Note 1: this is actually (inorder of right).back() == (postorder of right).back(), so if only there's no right subtree or the answer will always be false.

Note 2: we delete one node from postorder as we push one into stn.

Now we have [root, root's right] as stn and we check inorder.back() == stn.top()->val again.

true means inorder.back() is the root node and needs handled left case.
false means inorder.back() is the next right sub-node
So when we encounter a true, we will cache stn.top() as p and delete both nodes from inorder and stn.

Then we check inorder.size(), if there's no nodes left, it means p has no left node.

Else the next node in inorder could be p's left node or p's father which equals to the now stn.top() (remember we popped p from stn above).

If the latter happens, it means p has no left node and we need to move on to p's father(stn.top()).

If the former happens, it means p has one left node and it's postorder.back(), so we put it to p's left and delete it from the postorder and push the left node into stn 'cause it should be the next check node as the postorder is organized as above.

That's all of it. The algs just build a binary tree. :)

Inform me if there's anything vague or wrong, I'm open to any suggestions.
*/

class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        if(inorder.size() == 0)return NULL;
        TreeNode *p;
        TreeNode *root;
        stack<TreeNode *> stn;

        root = new TreeNode(postorder.back()); 
        stn.push(root); 
        postorder.pop_back(); 

        while(true)
        {
            if(inorder.back() == stn.top()->val) 
            {
                p = stn.top();
                stn.pop(); 
                inorder.pop_back(); 
                if(inorder.size() == 0) break;
                if(stn.size() && inorder.back() == stn.top()->val)
                    continue;
                p->left = new TreeNode(postorder.back()); 
                postorder.pop_back();
                stn.push(p->left);
            }
            else 
            {
                p = new TreeNode(postorder.back());
                postorder.pop_back();
                stn.top()->right = p; 
                stn.push(p); 
            }
        }
        return root;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值