Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:mac苹果电脑怎么删照片 编辑:程序博客网 时间:2024/06/05 02:07

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

Note:

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


以前写traversal的时候其实是死记硬背。。。谁在前谁在后,遇到这个题才这要搞懂。youtube有个人一步步给画了。不贴了

假设树 pre order为 a b c d e f g, 那么 a为root. 如果他的inorder 为 b c d a e f g 那么 bcd为左,def为右,然后递归的对左右做同样的操作。 


/** * Definition for binary tree * 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 helper(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);    }    TreeNode* helper(vector<int>& preorder, int pStart, int pEnd, vector<int>& inorder, int iStart, int iEnd){    if (pStart>pEnd)    return NULL;    if (pStart==pEnd)    return new TreeNode(preorder[pStart]);    int rootInd;    for (int i=iStart; i<=iEnd; i++){    if (inorder[i]==preorder[pStart]){    rootInd=i;    break;    }    }    TreeNode* root=new TreeNode(preorder[pStart]);    int leftLen=rootInd-iStart;    root->left=helper(preorder, pStart+1, pStart+leftLen, inorder, iStart, rootInd-1);    root->right=helper(preorder, pStart+leftLen+1, pEnd, inorder, rootInd+1, iEnd);    return root;    }};


0 0