LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal

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

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

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

解析:
给定二叉树的前序和中序遍历结果,构建二叉树。
前序遍历首先输出的是根节点,所有前序遍历的第一个数是根节点,即实例中的3,然后根节点在中序遍历结果中分割开左子树和右子树,即9是根节点3的左子树,15,20,7是根节点3的右子树,然后对左右子树,依次递归做相同处理即可。具体代码如下:

/**
 * 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) {
        return buildTree(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
    }
    TreeNode* buildTree(vector<int>& preorder, int pLeft, int pRight, vector<int>& inorder, int iLeft, int iRight)
    {
        if(pLeft > pRight || iLeft > iRight) return NULL;
        int i =0;
        for(i = iLeft; i <= iRight; ++i)
        {
            if(preorder[pLeft] == inorder[i])
                break;
        }
        TreeNode *cur = new TreeNode(preorder[pLeft]);
        cur->left = buildTree(preorder, pLeft + 1, pLeft+i-iLeft, inorder, iLeft, i-1);
        cur->right = buildTree(preorder, pLeft+i-iLeft+1, pRight, inorder, i+1, iRight);
        return cur;
    }
};


参考:
https://www.cnblogs.com/grandyang/p/4296500.html

One Comment

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据