Leetcode#106 Construct Binary Tree from Inorder and Postorder Traversal

原题地址

 

二叉树基本操作

[       ]O[              ]

[       ][              ]O

 

代码:

 1 TreeNode *restore(vector<int> &inorder, vector<int> &postorder, int ip, int pp, int len) {
 2   if (len == 0)
 3     return NULL;
 4 
 5   TreeNode *node = new TreeNode(postorder[pp + len - 1]);
 6 
 7   if (len == 1)
 8     return node;
 9 
10   int leftLen = 0;
11   while (inorder[ip + leftLen] != postorder[pp + len - 1])
12     leftLen++;
13   node->left = restore(inorder, postorder, ip, pp, leftLen);
14   node->right = restore(inorder, postorder, ip + leftLen + 1, pp + leftLen, len - leftLen - 1);
15 
16   return node;
17 }
18 
19 TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
20   return restore(inorder, postorder, 0, 0, inorder.size());
21 }

 

posted @ 2015-01-30 09:11  李舜阳  阅读(140)  评论(0编辑  收藏  举报