Boostable

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

LeetCode: Construct Binary Tree from Preorder and Inorder Traversal

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

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

地址:https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

算法:根据先序和中序构造出二叉树。代码:

 1 /**
 2  * Definition for binary tree
 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> &preorder, vector<int> &inorder) {
13         if(preorder.empty())    return NULL;
14         return subBuildTree(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
15     }
16     TreeNode *subBuildTree(vector<int> &preorder, vector<int> &inorder, int prebegin, int preend, int inbegin, int inend){
17         TreeNode *root = new TreeNode(preorder[prebegin]);
18         if(prebegin == preend && inbegin == inend){
19             return root;
20         }
21         int key = preorder[prebegin];
22         int i = inbegin;
23         while(i <= inend && inorder[i] != key)  ++i;
24         if(i > inbegin){
25             root->left = subBuildTree(preorder,inorder,prebegin+1,prebegin+i-inbegin,inbegin,i-1);
26         }
27         if(inend > i){
28             root->right = subBuildTree(preorder,inorder,prebegin+i-inbegin+1,preend,i+1,inend);
29         }
30         return root;
31     }
32 };

 

posted on 2014-08-27 21:34  Boostable  阅读(132)  评论(0编辑  收藏  举报