Leetcode#105 Construct Binary Tree from Preorder and Inorder Traversal

原题地址

 

基本二叉树操作。

O[       ][              ]

[       ]O[              ]

 

代码:

 1 TreeNode *restore(vector<int> &preorder, vector<int> &inorder, int pp, int ip, int len) {

 2   if (len <= 0)

 3     return NULL;

 4 

 5   TreeNode *node = new TreeNode(preorder[pp]);

 6 

 7   if (len == 1)

 8     return node;

 9 

10   int leftLen = 0;

11   while (inorder[ip + leftLen] != preorder[pp])

12     leftLen++;

13   node->left = restore(preorder, inorder, pp + 1, ip, leftLen);

14   node->right = restore(preorder, inorder, pp + leftLen + 1, ip + leftLen + 1, len - leftLen - 1);

15 

16   return node;

17 }

18 

19 TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {

20     return restore(preorder, inorder, 0, 0, preorder.size());

21 }

 

你可能感兴趣的:(LeetCode)