zoukankan      html  css  js  c++  java
  • 剑指offer:重建二叉树

    题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列为{1,2,4,7,3,5,6,8}和中序遍历的序列{4,7,2,1,5,3,8,6},则重建出下图所示的二叉树并输出它的头结点。


    分析:前序遍历的第一个元素就是根节点的值
    1. BinaryTreeNode* Construct(int* preorder, int* inorder, int length)
    2. {
    3. if(preorder == NULL || inorder == NULL || length <= 0)
    4. return NULL;
    5. return ConstructCore(preorder, preorder + length - 1,
    6. inorder, inorder + length - 1);
    7. }
    8. BinaryTreeNode* ConstructCore
    9. (
    10. int* startPreorder, int* endPreorder,
    11. int* startInorder, int* endInorder
    12. )
    13. {
    14. // 前序遍历序列的第一个数字是根结点的值
    15. int rootValue = startPreorder[0];
    16. BinaryTreeNode* root = new BinaryTreeNode();
    17. root->m_nValue = rootValue;
    18. root->m_pLeft = root->m_pRight = NULL;
    19. if(startPreorder == endPreorder)
    20. {
    21. if(startInorder == endInorder && *startPreorder == *startInorder)
    22. return root;
    23. else
    24. throw std::exception("Invalid input.");
    25. }
    26. // 在中序遍历中找到根结点的值
    27. int* rootInorder = startInorder;
    28. while(rootInorder <= endInorder && *rootInorder != rootValue)
    29. ++ rootInorder;
    30. if(rootInorder == endInorder && *rootInorder != rootValue)
    31. throw std::exception("Invalid input.");
    32. int leftLength = rootInorder - startInorder;
    33. int* leftPreorderEnd = startPreorder + leftLength;
    34. if(leftLength > 0)
    35. {
    36. // 构建左子树
    37. root->m_pLeft = ConstructCore(startPreorder + 1, leftPreorderEnd,
    38. startInorder, rootInorder - 1);
    39. }
    40. if(leftLength < endPreorder - startPreorder)
    41. {
    42. // 构建右子树
    43. root->m_pRight = ConstructCore(leftPreorderEnd + 1, endPreorder,
    44. rootInorder + 1, endInorder);
    45. }
    46. return root;
    47. }





  • 相关阅读:
    MySQL数据库之WHERE条件语句
    MySQL数据库的简单操作指令之DML语言
    课程设计必备之数据库操作代码模板
    MySQL数据库之外键约束的简单理解
    pdf.js的使用
    javascript连连看
    数据库问题
    列表文字超出后,鼠标悬浮显示全部内容
    springboot component注入servecie
    点击列表 获取table tr td 下的input value
  • 原文地址:https://www.cnblogs.com/zhuzhenfeng/p/4663539.html
Copyright © 2011-2022 走看看