[LeetCode][105,106] Construct Binary Tree from Inorder and (Post/Pre)order Traversal

Description:

Given (pre/post)order and inorder traversal of a tree, construct the binary tree.

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

——————————————————————————————————————————————————————————————————————————

Solution:

题意:通过前序遍历和中序遍历,或后序遍历和中序遍历,构造一棵二叉树。

思路:递归构造。


由前序遍历和中序遍历:

/**
 * 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 {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        this->preorder = preorder;
        this->inorder = inorder;
        return constructTree(0, 0, inorder.size() - 1);
    }
    TreeNode* constructTree(int preStart, int inStart, int inEnd) {
        if (preStart >= preorder.size() || inStart > inEnd)
            return NULL;
        int curIndex = 0;
        TreeNode* curRoot = new TreeNode(preorder[preStart]);
        for (int i = inStart; i <= inEnd; i++) {
            if (preorder[preStart] == inorder[i]) {
                curIndex = i;
                break;
            }
        }
        curRoot->left = constructTree(preStart + 1, inStart, curIndex - 1);
        curRoot->right = constructTree(preStart + curIndex - inStart + 1, curIndex + 1, inEnd);
        return curRoot;
    }
private:
    vector<int> preorder, inorder;
};

由后序遍历和中序遍历:

/**
 * 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 {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        this->postorder = postorder;
        this->inorder = inorder;
        return constructTree(postorder.size() - 1, 0, inorder.size() - 1);
    }
    TreeNode* constructTree(int postStart, int inStart, int inEnd) {
        if (postStart < 0 || inStart > inEnd)
            return NULL;
        int curIndex = 0;
        TreeNode* curRoot = new TreeNode(postorder[postStart]);
        for (curIndex = inStart; curIndex <= inEnd; curIndex++) 
            if (postorder[postStart] == inorder[curIndex]) 
                break;
        
        curRoot->left = constructTree(postStart - (inEnd - curIndex) - 1, inStart, curIndex - 1);
        curRoot->right = constructTree(postStart - 1, curIndex + 1, inEnd);
        return curRoot;
    }
private:
    vector<int> postorder, inorder;
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值