leetcode 105 /106 . Construct Binary Tree

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* buildTree(vector<int>& preorder, vector<int>& inorder) 
    {
        int len = preorder.size();
        return build(preorder,inorder,0,len-1,0,len-1);
    }

     TreeNode* build(vector<int>& preorder, vector<int>& inorder,int s,int e,int s1,int e1)
     {
         if(s>e ||s1>e1) return nullptr;
         TreeNode* root = new TreeNode(preorder[s]);
         int i = s1;
         for(;i<=e1;i++)//也可使用哈希表存储数值对应的下标
         {
             if(inorder[i] == preorder[s])
                 break;
         }
         root->left = build(preorder,inorder,s+1,s+i-s1,s1,i-1);
         root->right = build(preorder,inorder,s+i-s1+1,e,i+1,e1);
         return root;
     }
};

106 Construct Binary Tree from Inorder and Postorder Traversal

/** * 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) 
    {
        int len = inorder.size();
       return  BUILD(inorder,postorder,0,len-1,0,len-1);
    }

     TreeNode* BUILD(vector<int>& inorder, vector<int>& postorder,int s,int e,int s1,int e1)
     {

         if(s>e || s1>e1) return nullptr;
        TreeNode*root=new TreeNode(postorder[e1]);
        // int r = postorder[e];

         //root->val = r;
           int i = s;
        for (; i <= e; i++)
         {
             if(inorder[i] == postorder[e1])
                 break;
         }

         root->left = BUILD(inorder,postorder,s,i-1,s1,s1+i-s-1);
         root->right = BUILD(inorder,postorder,i+1,e,s1+i-s,e1-1);
         return root;
     }
};
点赞