LeetCode 106. 从中序与后序遍历序列构造二叉树(Construct Binary Tree from Inorder and Postorder Traversal)

题目描述

 

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

 

解题思路

 

利用回溯的思想,分别记录生成树时中序遍历和后序遍历对应的段首、段尾,每次构造树时首先构造根节点为后序遍历的尾节点,接着在中序遍历序列中找到根的位置,然后根左对应左子树,根右对应右子树,对应到后序遍历序列中分隔成两段,递归构造左子树和右子树。

 

代码

 

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
13         return build(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
14     }
15     TreeNode* build(vector<int> inorder, vector<int> postorder, int iLeft, int iRight, int pLeft, int pRight){
16         if(pLeft > pRight) return NULL;
17         TreeNode* root = new TreeNode(postorder[pRight]);
18         int idx = iLeft;
19         while(inorder[idx] != postorder[pRight]) idx++;
20         root->left = build(inorder, postorder, iLeft, idx - 1, pLeft, pLeft + idx - iLeft - 1);
21         root->right = build(inorder, postorder, idx + 1, iRight, pLeft + idx - iLeft, pRight - 1);
22         return root;
23     }
24 };

 

posted @ 2018-08-21 11:25  FlyingWarrior  阅读(656)  评论(0编辑  收藏  举报