溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C++怎么實現(xiàn)由先序和中序遍歷二叉樹

發(fā)布時間:2022-03-28 15:31:19 來源:億速云 閱讀:286 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要介紹了C++怎么實現(xiàn)由先序和中序遍歷二叉樹的相關(guān)知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇C++怎么實現(xiàn)由先序和中序遍歷二叉樹文章都會有所收獲,下面我們一起來看看吧。

由先序和中序遍歷建立二叉樹

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

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

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Return the following binary tree:

    3
/
9  20

15   7

這道題要求用先序和中序遍歷來建立二叉樹,跟之前那道 Construct Binary Tree from Inorder and Postorder Traversal 原理基本相同,針對這道題,由于先序的順序的第一個肯定是根,所以原二叉樹的根節(jié)點可以知道,題目中給了一個很關(guān)鍵的條件就是樹中沒有相同元素,有了這個條件就可以在中序遍歷中也定位出根節(jié)點的位置,并以根節(jié)點的位置將中序遍歷拆分為左右兩個部分,分別對其遞歸調(diào)用原函數(shù),參見代碼如下:

class Solution {
public:
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        return buildTree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
    }
    TreeNode *buildTree(vector<int> &preorder, int pLeft, int pRight, vector<int> &inorder, int iLeft, int iRight) {
        if (pLeft > pRight || iLeft > iRight) return NULL;
        int i = 0;
        for (i = iLeft; i <= iRight; ++i) {
            if (preorder[pLeft] == inorder[i]) break;
        }
        TreeNode *cur = new TreeNode(preorder[pLeft]);
        cur->left = buildTree(preorder, pLeft + 1, pLeft + i - iLeft, inorder, iLeft, i - 1);
        cur->right = buildTree(preorder, pLeft + i - iLeft + 1, pRight, inorder, i + 1, iRight);
        return cur;
    }
};

下面來看一個例子, 某一二叉樹的中序和后序遍歷分別為:

Preorder:    5  4  11  8  13  9

Inorder:    11  4  5  13  8  9

5  4  11  8  13  9      =>          5

11  4  5  13  8  9                /  

4  11     8   13  9      =>         5

11  4     13  8  9                  /  

                             4   8

11       13    9        =>         5

11       13    9                    /  

                             4   8

                            /    /    

                           11    13    9

做完這道題后,大多人可能會有個疑問,怎么沒有由先序和后序遍歷建立二叉樹呢,這是因為先序和后序遍歷不能唯一的確定一個二叉樹,比如下面五棵樹:

1      preorder:    1  2  3
/        inorder:       2  1  3
2 3       postorder:   2  3  1

1       preorder:     1  2  3
/       inorder:       3  2  1
2          postorder:   3  2  1
/
3

1        preorder:    1  2  3
/        inorder:      2  3  1
2       postorder:  3  2  1

3

       1         preorder:    1  2  3
       inorder:      1  3  2
2      postorder:  3  2  1
/
3

       1         preorder:    1  2  3
     inorder:      1  2  3
2      postorder:  3  2  1

3

關(guān)于“C++怎么實現(xiàn)由先序和中序遍歷二叉樹”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“C++怎么實現(xiàn)由先序和中序遍歷二叉樹”知識都有一定的了解,大家如果還想學習更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI