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.

思路:



如果所示的二叉树,前序遍历: 4 1 3 2 7 6 5 

    后序遍历: 3 1 2 4 6 7 5


前序遍历中开始存放的是根节点,所以第一个就是根节点。然后再中序遍历中寻找那个根节点,找到其索引值,然后我们发现从一开始到这个索引值对应的数值,也就是这个根节点,这一部分全部是左边的节点,有半部分全部是右边的节点。

如此递归即可。

代码:

/**
 * 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 preStart=0,preEnd=preorder.size()-1;
        int inStart=0,inEnd=inorder.size()-1;
        
        return constructHelper(preorder,preStart,preEnd,
                inorder, inStart,inEnd);
    }
    
    TreeNode* constructHelper(vector<int>&preorder,int preStart,int preEnd,
                vector<int>&inorder,int inStart,int inEnd){
        if(preStart>preEnd||inStart>inEnd)  return NULL;
        
        int val=preorder[preStart];
        TreeNode*p =new TreeNode(val);
        int k=0;
        for(int i=0;i<inorder.size();i++){
            if(inorder[i]==val){
                k=i;break;
            } 
        }
        
        p->left= constructHelper(preorder,preStart+1,preStart+(k-inStart),
                inorder, inStart,k-1);//k之前
                //k-start  考虑这种情况,在找到右子树的左子树的时候
                //k在右边,inStart也在右边,此时需要找的是左边的个数,
                //k-inStart 就解决了这个问题
        p->right=constructHelper(preorder,preStart+(k-inStart)+1, preEnd,
                inorder,k+1, inEnd); 
        return p;        
    } 
};


原文地址:https://www.cnblogs.com/jsrgfjz/p/8519839.html