温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++怎么实现由先序和中序遍历二叉树

发布时间:2022-03-28 15:31:19 来源:亿速云 阅读:188 作者:iii 栏目:大数据

这篇文章主要介绍了C++怎么实现由先序和中序遍历二叉树的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇C++怎么实现由先序和中序遍历二叉树文章都会有所收获,下面我们一起来看看吧。

由先序和中序遍历建立二叉树

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 原理基本相同,针对这道题,由于先序的顺序的第一个肯定是根,所以原二叉树的根节点可以知道,题目中给了一个很关键的条件就是树中没有相同元素,有了这个条件就可以在中序遍历中也定位出根节点的位置,并以根节点的位置将中序遍历拆分为左右两个部分,分别对其递归调用原函数,参见代码如下:

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

关于“C++怎么实现由先序和中序遍历二叉树”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“C++怎么实现由先序和中序遍历二叉树”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI