105. Construct Binary Tree from Preorder and Inorder Traversal

Posted 为了更优秀的你,加油!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

解题思路:最经典的递归,已知先序和中序,构造树

/**
 * 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* build(vector<int>& preorder, vector<int>& inorder, int pleft, int pright, int ileft, int iright){
        if(pleft == pright)return new TreeNode(preorder[pleft]);
        if(pleft > pright)return NULL;
        int pos;
        TreeNode* root = new TreeNode(preorder[pleft]);
        for(pos = ileft;pos <= iright; pos++){
            if(inorder[pos] == preorder[pleft])break;
        }
        int lefthalf=pos-ileft;
        int righthalf=iright-pos;
        root->left = build(preorder,inorder,pleft+1,pleft+lefthalf,ileft,pos-1);
        root->right = build(preorder,inorder,pright-righthalf+1,pright,pos+1,iright);
        return root;        
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return build(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
    }
};

 

以上是关于105. Construct Binary Tree from Preorder and Inorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

105. Construct Binary Tree from Preorder and Inorder Traversal

105. Construct Binary Tree from Preorder and Inorder Traversal

105.Construct Binary Tree from Preorder and Inorder Traversal

105. Construct Binary Tree from Preorder and Inorder Traversal

105. Construct Binary Tree from Preorder and Inorder Traversal

105. Construct Binary Tree from Preorder and Inorder Traversal