105. Construct Binary Tree from Preorder and Inorder Traversal(构建二叉树) [LeetCode]

 

105Construct Binary Tree from Preorder and Inorder Traversal

For example, given:

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

画了一个复杂点的二叉树来剖析本题的递归,注意尾递归不在搜索范围内,只是用来确定边界,边界一定要考虑清除!

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

private:
    TreeNode *buildTree(int *preorder, int *inorder, int size) {
        if (NULL == preorder || NULL == inorder || size <= 0) return NULL;

        TreeNode *root = new TreeNode(preorder[0]);
        if (size == 1)  //recursion terminate, trace back
            return root;

        int rootIndex = 0;  //search the root index in inorder
        for (; rootIndex < size; rootIndex++)
            if (inorder[rootIndex] == root->val) break;

        root->left = buildTree(&preorder[1], inorder, rootIndex);
        root->right = buildTree(&preorder[rootIndex + 1], &inorder[rootIndex + 1], size - rootIndex - 1);

        return root;
    }
};

 

 

106Construct Binary Tree from Inorder and Postorder Traversal

given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

同样以上面的图为例来说明:

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

        TreeNode *root = new TreeNode(postorder[size-1]);
        if (size == 1)  //recursion terminate, trace back
            return root;

        int rootIndex = 0;  //search the root index in inorder
        for (; rootIndex < size; rootIndex++)
            if (inorder[rootIndex] == root->val) break;

        root->left = buildTree(&postorder[0], inorder, rootIndex);
        root->right = buildTree(&postorder[rootIndex], &inorder[rootIndex + 1], size - rootIndex - 1);

        return root;
    }
};

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luuyiran

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值