您好,登錄后才能下訂單哦!
這篇文章主要介紹了C++怎么實現(xiàn)由中序和后序遍歷二叉樹的相關(guān)知識,內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇C++怎么實現(xiàn)由中序和后序遍歷二叉樹文章都會有所收獲,下面我們一起來看看吧。
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/
9 20
/
15 7
這道題要求從中序和后序遍歷的結(jié)果來重建原二叉樹,我們知道中序的遍歷順序是左-根-右,后序的順序是左-右-根,對于這種樹的重建一般都是采用遞歸來做,可參見博主之前的一篇博客 Convert Sorted Array to Binary Search Tree。針對這道題,由于后序的順序的最后一個肯定是根,所以原二叉樹的根結(jié)點可以知道,題目中給了一個很關(guān)鍵的條件就是樹中沒有相同元素,有了這個條件就可以在中序遍歷中也定位出根節(jié)點的位置,并以根節(jié)點的位置將中序遍歷拆分為左右兩個部分,分別對其遞歸調(diào)用原函數(shù)。代碼如下:
class Solution { public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1); } TreeNode *buildTree(vector<int> &inorder, int iLeft, int iRight, vector<int> &postorder, int pLeft, int pRight) { if (iLeft > iRight || pLeft > pRight) return NULL; TreeNode *cur = new TreeNode(postorder[pRight]); int i = 0; for (i = iLeft; i < inorder.size(); ++i) { if (inorder[i] == cur->val) break; } cur->left = buildTree(inorder, iLeft, i - 1, postorder, pLeft, pLeft + i - iLeft - 1); cur->right = buildTree(inorder, i + 1, iRight, postorder, pLeft + i - iLeft, pRight - 1); return cur; } };
上述代碼中需要小心的地方就是遞歸是 postorder 的左右 index 很容易寫錯,比如 pLeft + i - iLeft - 1, 這個又長又不好記,首先我們要記住 i - iLeft 是計算 inorder 中根節(jié)點位置和左邊起始點的距離,然后再加上 postorder 左邊起始點然后再減1。我們可以這樣分析,如果根結(jié)點就是左邊起始點的話,那么拆分的話左邊序列應(yīng)該為空集,此時 i - iLeft 為0, pLeft + 0 - 1 < pLeft, 那么再遞歸調(diào)用時就會返回 NULL, 成立。如果根節(jié)點是左邊起始點緊跟的一個,那么 i - iLeft 為1, pLeft + 1 - 1 = pLeft,再遞歸調(diào)用時還會生成一個節(jié)點,就是 pLeft 位置上的節(jié)點,為原二叉樹的一個葉節(jié)點。
下面來看一個例子, 某一二叉樹的中序和后序遍歷分別為:
Inorder: 11 4 5 13 8 9
Postorder: 11 4 13 9 8 5
11 4 5 13 8 9 => 5
11 4 13 9 8 5 /
11 4 13 8 9 => 5
11 4 13 9 8 /
4 8
11 13 9 => 5
11 13 9 /
4 8
/ /
11 13 9
關(guān)于“C++怎么實現(xiàn)由中序和后序遍歷二叉樹”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“C++怎么實現(xiàn)由中序和后序遍歷二叉樹”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。