[leetCode]Construct Binary Tree from Preorder and Inorder Traversal

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

给了前序和中序遍历,这个题也好做,主要问题是把左右分支的下标给搞清楚。

对于前序来说,本次的根节点总是第一个preorder[0];左子树坐标是[prestart+1,prestart+i],右子树是[prestart+i+1,preend];

而对于中序来说,如果根节点是第i个(从instart开始数),那么左边子树的坐标是[instart,instart+i-1],右子树是[instart+i+1,inend];

如果觉得前序不好算的话,可以先算中序,前序的左子树段是中序左子树段+1(但是要注意初始坐标不一样)

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 struct TreeNode {
 5     int val;
 6     TreeNode  *left;
 7     TreeNode  *right;
 8     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 9 };
10 class Solution {
11 public:
12     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
13         TreeNode * head = build(preorder,0,preorder.size()-1,inorder,0, inorder.size()-1);
14         return head;
15     }
16 
17     TreeNode *build(vector<int> &preorder, int preStart,int preEnd,vector<int> &inorder, int inStart, int inEnd){
18         if(preStart == preEnd) return new TreeNode(preorder[preStart]);
19         if(preStart > preEnd)    return NULL;
20         int head = preorder[preStart];
21         int i = 0;
22         int size = preEnd - preStart+1;
23         for(; i<size;i++){
24             if(inorder[i+inStart] == head){
25                 break;
26             }
27         }
28         TreeNode *node = new TreeNode(head);
29         node->left = build(preorder,preStart+1,preStart+i,inorder, inStart, inStart+i-1);
30         node->right = build(preorder, preStart+1+i,preEnd,inorder,inStart+1+i,inEnd);
31         return node;
32 
33     }
34 };

 

 

 

posted @ 2014-03-13 21:46  青轰的后花园  阅读(153)  评论(0编辑  收藏  举报