leetcode 105-106:Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:炉石传说当地网络 编辑:程序博客网 时间:2024/05/02 14:34

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

Note:

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

/** * 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) {        if(preorder.size()==0)            return NULL ;        return dfs(preorder.begin(),preorder.end(),inorder.begin(),inorder.end());    }    //不包括preEnd,inEnd    TreeNode* dfs(vector<int>::iterator preStart,vector<int>::iterator preEnd,vector<int>::iterator inStart,vector<int>::iterator inEnd) {        if(preStart==preEnd)            return NULL;        TreeNode* root=new TreeNode(*preStart);        vector<int>::iterator it=find(inStart,inEnd,root->val);        int leftSize=it-inStart;        root->left=dfs(preStart+1,preStart+1+leftSize,inStart,it);        root->right=dfs(preStart+1+leftSize,preEnd,it+1,inEnd);        return root;    }};


106:Given inorder and postorder traversal of a tree, construct the binary tree.

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


/** * 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>& inorder, vector<int>& postorder) {        if(inorder.size()==0)            return NULL;        return dfs(inorder.begin(),inorder.end(),postorder.begin(),postorder.end());    }    TreeNode* dfs(vector<int>::iterator inStart,vector<int>::iterator inEnd,vector<int>::iterator pStart,vector<int>::iterator pEnd){        if(inStart==inEnd)            return NULL;        TreeNode* root=new TreeNode(*(pEnd-1));        vector<int>::iterator it=find(inStart,inEnd,root->val);        int leftSize=it-inStart;        root->left=dfs(inStart,it,pStart,pStart+leftSize);        root->right=dfs(it+1,inEnd,pStart+leftSize,pEnd-1);        return root;    }};



0 0
原创粉丝点击