LeetCode(Construct Binary Tree from Inorder and Postorder Traversal)根据二叉树的中序和后续构造二叉树

题目要求:

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

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

代码:

 TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
    if(inorder.size() == 0 || postorder.size() == 0 || inorder.size() != postorder.size())
      return NULL;
    TreeNode* root = DFS(inorder, 0, inorder.size() - 1,
                         postorder, 0, postorder.size() - 1);
    return root;
  }
  
  TreeNode* DFS(vector<int>& inorder, int in_start, int in_end,
                vector<int>& postorder, int post_start, int post_end)
  {
    int root_value = postorder[post_end];
    TreeNode* root = new TreeNode(root_value);
    if(post_start == post_end)
    {
      if(in_start == in_end && inorder[in_start] == root_value)
        return root;
      else 
        throw ("Input error");
    }
    int root_in_idx = in_start;
    while(root_in_idx <= in_end && inorder[root_in_idx] != root_value )
    {
      ++root_in_idx;
    }
    if(root_in_idx > in_end)
    {
      throw("input error");
    }
    int left_len = root_in_idx - in_start;
    int left_pos_end = post_start + left_len;
    if(left_len > 0)
      root->left = DFS(inorder, in_start, root_in_idx - 1,
                       postorder, post_start, left_pos_end - 1);
    if(left_len < (post_end - post_start))
      root->right = DFS(inorder, root_in_idx + 1, in_end,
                        postorder, left_pos_end, post_end - 1);
    return root;
  }


你可能感兴趣的:(LeetCode,面试,二叉树,构造二叉树)