1. 程式人生 > >105 Construct Binary Tree from Preorder and Inorder Traversal 從前序與中序遍歷序列構造二叉樹

105 Construct Binary Tree from Preorder and Inorder Traversal 從前序與中序遍歷序列構造二叉樹

leet blog pub struct class null true ems inorder

給定一棵樹的前序遍歷與中序遍歷,依據此構造二叉樹。
註意:
你可以假設樹中沒有重復的元素。
例如,給出
前序遍歷 = [3,9,20,15,7]
中序遍歷 = [9,3,15,20,7]
返回如下的二叉樹:
3
/ \
9 20
/ \
15 7
詳見:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/

/**
 * 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) {
        int is=inorder.size();
        if(is==0||inorder.empty())
        {
            return nullptr;
        }
        int val=preorder[0];
        TreeNode* root=new TreeNode(val);
        vector<int> pre_left,pre_right,in_left,in_right;
        int p=0;
        for(;p<is;++p)
        {
            if(inorder[p]==val)
            {
                break;
            }
        }
        for(int i=0;i<is;++i)
        {
            if(i<p)
            {
                pre_left.push_back(preorder[i+1]);
                in_left.push_back(inorder[i]);
            }
            else if(i>p)
            {
                pre_right.push_back(preorder[i]);
                in_right.push_back(inorder[i]);
            }
        }
        root->left=buildTree(pre_left,in_left);
        root->right=buildTree(pre_right,in_right);
        return root;
    }
};

105 Construct Binary Tree from Preorder and Inorder Traversal 從前序與中序遍歷序列構造二叉樹