105. Construct Binary Tree from Preorder and Inorder Traversal 由先序和中序遍历建立二叉树

题目链接

tag:

  • Medium;

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

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

Example:

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
 / \
15 7

思路:
  由于先序的顺序的第一个肯定是根,所以原二叉树的根节点可以知道,题目中给了一个很关键的条件就是树中没有相同元素,有了这个条件我们就可以在中序遍历中也定位出根节点的位置,并以根节点的位置将中序遍历拆分为左右两个部分,分别对其递归调用原函数即可。代码如下:

/**
 * 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& preorder, vector& inorder) {
        if (preorder.size() != inorder.size()) return NULL;
        return buildTree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
    }
    
    TreeNode* buildTree(vector& preorder, int preLeft, int preRight, vector& inorder, int inLeft, int inRight) {
        if (preLeft > preRight || inLeft > inRight) return NULL;
        int i = 0;
        for (i=inLeft; ileft = buildTree(preorder, preLeft + 1, preLeft+i-inLeft, inorder, inLeft, i-1);
        cur->right = buildTree(preorder, preLeft+i-inLeft+1, preRight, inorder, i+1, inRight);
        return cur;
    }
};

你可能感兴趣的:(105. Construct Binary Tree from Preorder and Inorder Traversal 由先序和中序遍历建立二叉树)