[LeetCode] Construct Binary Tree from Preorder and Inorder Traversal

來源:互聯網
上載者:User

標籤:style   blog   color   strong   for   io   

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

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

 

方法一:最先想到的就是遞迴,注意low、high的計算,還有初始時NULL情況的處理。。

從inorder中尋找pre的第一個,然後左右遞迴

 1 class Solution 2 { 3     public: 4         TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) 5         { 6             if(preorder.size() == 0 || inorder.size() == 0) 7                 return NULL; 8             return buildTree(preorder, 0, preorder.size()-1, 9                               inorder, 0, inorder.size()-1);10         }     11               12         TreeNode *buildTree(vector<int> &preorder, int low1, int high1,13                             vector<int> &inorder, int low2, int high2)14         {     15             //cout << "==============" <<endl;16             //cout << "low1 = \t" << low1 <<endl;17             //cout << "high1= \t" << high1 <<endl;18             //cout << "low2 = \t" << low2 <<endl;19             //cout << "high2= \t" << high2 <<endl;20               21             TreeNode * p = new TreeNode(preorder[low1]);22             if(low1 == high1)23             {   24                 return p;25             }   26             int index = 0;27             for(index = low2; index < high2; index++)28             {   29                 if(inorder[index] == preorder[low1])30                     break;31             }32             //cout << "index= \t" << index<<endl;33 34             if(index != low2)35                 p->left = buildTree(preorder, low1+1,(low1+1) + (index-1-low2), inorder, low2, index-1);36             if(index != high2)37                 p->right = buildTree(preorder, high1 - (high2-index-1) ,high1, inorder, index+1, high2);38 39             return p;40         }41 } ;

方法二:迭代

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.