重建二叉树
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | /* * 二叉树的遍历方式: * 前序遍历:先访问根节点,再访问左子节点,最后访问右子节点。 * 中序遍历:先访问左子节点,再访问根节点,最后访问右子节点。 * 后序遍历:先访问左子节点,再访问右子节点,最后访问根节点。 */ /* * 输入二叉树的前序遍历和中序遍历的结果,请重新构建该二叉树。 * 假设前序遍历和中序遍历的结果中都不含重复的数字。例如输入 * 的前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}, * 则构建出所对应的二叉树,并返回根节点。 */ /* * 在二叉树的前序遍历序列中,第一个数字总是树的根节点的值。在中序遍历中, * 根节点的值在序列的中间,左子树的节点的值位于根节点值的左边,右子树的节点的 * 值位于根结点的值的右边。 */ #include<iostream> using namespace std; struct BinaryTreeNode { int m_nValue; BinaryTreeNode* m_pLeft; BinaryTreeNode* m_pRight; }; BinaryTreeNode* ConstructCore( int * startPreorder, int * endPreorder, int * startInorder, int * endInorder) { //前序遍历序列的第一个数字是根节点的值 int rootValue = startPreorder[0]; BinaryTreeNode* root = new BinaryTreeNode(); root->m_nValue = rootValue; root->m_pLeft = root->m_pRight = nullptr ; if (startPreorder == endPreorder) { if (startInorder == endInorder && *startPreorder == *endPreorder) { return root; } else { throw std::exception( "Invalid input." ); } } //在中序遍历中找到根节点的值 int * rootInorder = startInorder; while (rootInorder <= endInorder && *rootInorder != rootValue) { ++rootInorder; } if (rootInorder == endInorder && *rootInorder != rootValue) { throw std::exception( "Invalid input." ); } int leftLength = rootInorder - startInorder; int * leftPreorderEnd = startPreorder + leftLength; if (leftLength > 0) { //构建左子树 root->m_pLeft = ConstructCore(startPreorder + 1, leftPreorderEnd, startInorder, rootInorder - 1); } if (leftLength < endPreorder - startPreorder) { root->m_pRight = ConstructCore(leftPreorderEnd + 1, endPreorder, rootInorder + 1, endInorder); } return root; } BinaryTreeNode* Construct( int * preorder, int * inorder, int length) { if (preorder == nullptr || inorder == nullptr || length <= 0) { return nullptr ; } return ConstructCore(preorder, preorder + length - 1, inorder, inorder + length - 1); } int main() { int preOrder[] = { 1,2,4,7,3,5,6,8 }; int inOrder[] = { 4,7,2,1,5,3,8,6 }; BinaryTreeNode* root = Construct(preOrder, inOrder, 8); return 0; } |
posted on 2021-11-11 08:25 xcxfury001 阅读(13) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用