LeetCode105. Construct Binary Tree from Preorder and Inorder Traversal

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

题目:根据给定的二叉树的前序和中序排列,重建二叉树。假设树中没有元素重复。

思路:参见解析。因为前序排列preorder根结点root总是在前,那么我们可以在中序inorder中查找root的位置,假设在in_root_index,那么对于中序排列来说,在in_root_index左侧的就是root对应的左子树,右侧的为其右子树。同时再对preorder中的元素进行划分,确定哪些是root对应左子树的元素,而哪些是右子树的元素,确定的方法是我们可以通过计算中序排列inorder中左子树的长度来推出前序排列preorder中右子树应该开始的地方:preorder左子树的长度等于inorder左子树的长度,pre_start + in_root_index - in_start + 1。对子树按照如上方法进行遍历。

工程代码下载

/**
 * 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(0, 0, inorder.size()-1, preorder, inorder);
    }
private:
    TreeNode* buildTree(int pre_start, int in_start, int in_end, 
                       vector<int>& preorder, vector<int>& inorder)
    {
        if(pre_start >= preorder.size() ||  in_start > in_end){
            return nullptr;
        }

        TreeNode* root = new TreeNode(preorder[pre_start]);
        int in_root_index =0;
        for(int i=in_start; i<=in_end; ++i){
            if(inorder[i] == root->val){
                in_root_index = i;
                break;
            }
        }
        root->left = buildTree(pre_start + 1, in_start, in_root_index - 1,
                              preorder, inorder);
        root->right = buildTree(pre_start + in_root_index - in_start + 1,
                               in_root_index + 1, in_end,
                               preorder, inorder);
        return root;
    }
};
上一篇:robotframework 导入python包


下一篇:LeetCode-230 Kth Smallest Element in a BST