4/21/2014

Leetcode -- Construct Binary Tree from Inorder and Postorder Traversal

 /**  
  * Definition for binary tree  
  * struct TreeNode {  
  *   int val;  
  *   TreeNode *left;  
  *   TreeNode *right;  
  *   TreeNode(int x) : val(x), left(NULL), right(NULL) {}  
  * };  
  */  
 class Solution {  
 public:  
   TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {  
     if(inorder.empty() || postorder.empty()) {  
       return NULL;  
     }  
     return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);  
   }  
   TreeNode * buildTree(vector<int>& inorder, int iStart, int iEnd, vector<int>& postorder, int pStart, int pEnd) {  
     if(iStart > iEnd || pStart > pEnd) {  
       return NULL;  
     }  
     TreeNode * root = new TreeNode (postorder[pEnd]);  
     int i = iStart;  
     for(; i <= iEnd; ++i) {  
       if(inorder[i] == postorder[pEnd]) {  
         break;  
       }  
     }  
     root->left = buildTree(inorder, iStart, i - 1, postorder, pStart, pStart + i - iStart - 1);  
     root->right = buildTree(inorder, i + 1, iEnd, postorder, pEnd + i - iEnd, pEnd - 1);  
     return root;  
   }  
 };  

3 comments:

Unknown said...

No words at all?

Unknown said...

How do you get that alternative colors for each neighboring line? My code blocks are just grey all over.

Everett Roger Qin said...

There is a site called codeformatter, you can google it