木落长安rr

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

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

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

中序、后序遍历得到二叉树,可以知道每一次新数组的最后一个数为当时子树的根节点,每次根据中序遍历的根节点的左右两边确定左右子树,再对应后序的左右子树,不停递归得到根节点,可以建立二叉树。每次由循环得到根节点在中序数组中坐标i

由中序遍历知:每一次inorder的左子树范围[ileft,i-1],右子树范围[i+1,iright]

由后序遍历知:每一次postorder的左子树范围[pleft,pleft+i-ileft-1],右子树范围[pleft+i-ileft,pright-1]。C++

 1 TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
 2         return buildTree(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
 3     }
 4     
 5     TreeNode* buildTree(vector<int>& inorder,int ileft,int iright,vector<int>& postorder,int pleft,int pright){
 6         if(ileft>iright||pleft>pright)
 7             return NULL;
 8         TreeNode* root=new TreeNode(postorder[pright]);
 9         int i=0;
10         for(i=ileft;i<=iright;i++){
11             if(inorder[i]==postorder[pright])
12                 break;
13         }
14         root->left=buildTree(inorder,ileft,i-1,postorder,pleft,pleft+i-ileft-1);
15         root->right=buildTree(inorder,i+1,iright,postorder,pleft+i-ileft,pright-1);
16         return root;
17     }

 

posted on 2019-04-15 22:03  木落长安rr  阅读(196)  评论(0编辑  收藏  举报