重建二叉树(C++和Python实现)
(说明:本博客中的题目、题目详细说明及参考代码均摘自 “何海涛《剑指Offer:名企面试官精讲典型编程题》2012年”)
题目
输入某二叉树前序遍历和中序遍历结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
进一步详细说明:
例如输入前序遍历序列 {1, 2, 4, 7, 3, 5, 6, 8} 和 中序遍历序列 {4, 7, 2, 1, 5, 3, 8, 6}, 则重建出图2.6所示的二叉树并输出它的头结点。二叉树结点的定义如下:
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
算法设计思想
前序遍历序列的第一个元素为根结点的值,然后在中序遍历序列中寻找根节点的值的位置(索引)。
从中序遍历序列的起始位置到根结点的值的位置(不包含)为根结点左子树的中序遍历序列;从中序遍历序列的根结点的值的位置(不包含)到结束位置为根结点右子树的中序遍历序列;相应的,从前序遍历序列的第二个元素开始的根结点左子树结点数个元素的子序列为根结点左子树的前序遍历序列,从下一个元素开始,直到结束位置的子序列为根结点右子树的前序遍历序列。如图 2.7 所示,
C++ 实现
#include <stdio.h>
#include <stdlib.h> // exit() struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
}; BinaryTreeNode* ConstructCore(int* preorderSta, int* preorderEnd, int* inorderSta, int* inorderEnd)
{
// Create binary tree root node
BinaryTreeNode* root = new BinaryTreeNode;
root->m_nValue = *preorderSta;
root->m_pLeft = root->m_pRight = NULL;
// Base condition
if (preorderSta == preorderEnd)
{
if (inorderSta == inorderEnd && *preorderSta == *inorderSta) // 易漏点
return root;
else {
printf("Invalid input: line %d in Function %s.\n", __LINE__, __func__);
exit(-);
}
}
// Find root node position in in-order sequence
int* rootInorder = inorderSta;
while (rootInorder < inorderEnd && *rootInorder != *preorderSta) // 易错点,注意比较符号,没有等号。
++ rootInorder; if (rootInorder == inorderEnd && *rootInorder != *preorderSta) { // 易漏点
printf("Invalid input: line %d in Function %s.\n", __LINE__, __func__);
exit(-);
} // Construct left subtree
if (rootInorder > inorderSta)
root->m_pLeft = ConstructCore(preorderSta+, preorderSta+(rootInorder-inorderSta), inorderSta, rootInorder-); // Construct right subtree
if (rootInorder < inorderEnd)
root->m_pRight = ConstructCore(preorderSta+(rootInorder-inorderSta)+, preorderEnd, rootInorder+, inorderEnd); return root;
} // Re-construct the binary tree, then return the root node pointer
BinaryTreeNode* Construct(int* preorder, int* inorder, int nodesNum)
{
if (preorder == NULL || inorder == NULL || nodesNum <= ) // 易漏点
return NULL; return ConstructCore(preorder, preorder+nodesNum-, inorder, inorder+nodesNum-);
} // Destroy Binary Tree
void destroyBinaryTree(BinaryTreeNode* &root)
{
if (root != NULL) // 易漏点
{
// Postorder traversalif (root->m_pLeft != NULL)
destroyBinaryTree(root->m_pLeft);
if (root->m_pRight != NULL)
destroyBinaryTree(root->m_pRight);
delete root;
root = NULL; // 易漏点
}
} // Print binary tree elements in post-traversal
void printBinaryTree(const BinaryTreeNode* root)
{
if (root) // 易漏点
{
printBinaryTree(root->m_pLeft);
printBinaryTree(root->m_pRight);
printf("%d, ", root->m_nValue);
}
} void unitest()
{
int preorderArr[] = {, , , , , , , };
int inorderArr[] = {, , , , , , , }; int nodesNum = sizeof(preorderArr)/sizeof(preorderArr[]);
// Re-construct Binary tree from preorder sequence and inorder sequence
BinaryTreeNode* root = Construct(preorderArr, inorderArr, nodesNum);
// Print Binary Tree
printBinaryTree(root);
// Destroy Binary Tree
destroyBinaryTree(root);
} int main()
{
unitest(); return ;
}
Python 实现
#!/usr/bin/python
# -*- coding: utf8 -*- class BinaryTreeNode:
def __init__(self, value, left_node=None, right_node=None):
self.value = value
self.left_node = left_node
self.right_node = right_node def print_binarytree_postorder(head):
if head:
print_binarytree_postorder(head.left_node)
print_binarytree_postorder(head.right_node)
print "%d, " % head.value, def construct(preorder, inorder, nodes_num):
if (preorder is None) or (inorder is None) or (nodes_num <= 0):
return None return construct_core(preorder, 0, nodes_num-1, inorder, 0, nodes_num-1) def construct_core(preorder, start_index_preorder, end_index_preorder,
inorder, start_index_inorder, end_index_inorder):
# Create root node
root = BinaryTreeNode(preorder[start_index_preorder])
# Base condition
if start_index_preorder == end_index_preorder:
if (start_index_inorder == end_index_inorder) and (preorder[start_index_preorder] == inorder[start_index_inorder]):
return root
else:
print "Invalid input!"
exit(-1)
# Recursive condition
root_index_inorder = start_index_inorder
while (root_index_inorder < end_index_inorder) and (inorder[root_index_inorder] != preorder[start_index_preorder]):
root_index_inorder += 1 if (root_index_inorder == end_index_inorder) and (inorder[root_index_inorder] != preorder[start_index_preorder]):
print "Invalid input!"
exit(-1)
# Construct left subtree
if root_index_inorder > start_index_inorder:
root.left_node = construct_core(preorder, start_index_preorder+1, start_index_preorder+root_index_inorder-start_index_inorder,
inorder, start_index_inorder, root_index_inorder-1)
# Construct right subtree
if root_index_inorder < end_index_inorder:
root.right_node = construct_core(preorder, start_index_preorder+root_index_inorder-start_index_inorder+1, end_index_preorder,
inorder, root_index_inorder+1, end_index_inorder) return root def unitest():
preorder_list = [1, 2, 4, 7, 3, 5, 6, 8]
inorder_list = [4, 7, 2, 1, 5, 3, 8, 6]
# Reconstruct binary tree, then return root node
root_binarytree = construct(preorder_list, inorder_list, len(preorder_list))
# Print Binary Tree
print_binarytree_postorder(root_binarytree) if __name__ == '__main__':
unitest()
参考代码
1. targetver.h (06_ConstructBinaryTree/ 目录)
#pragma once // The following macros define the minimum required platform. The minimum required platform
// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run
// your application. The macros work by enabling all features available on platform versions up to and
// including the version specified. // Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
2. stdafx.h (06_ConstructBinaryTree/ 目录)
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
// #pragma once #include "targetver.h" #include <stdio.h>
#include <tchar.h> // TODO: reference additional headers your program requires here
3. stdafx.cpp (06_ConstructBinaryTree/ 目录)
// stdafx.cpp : source file that includes just the standard includes
// ConstructBinaryTree.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H
// and not in this file
4. ConstructBinaryTree.cpp
// ConstructBinaryTree.cpp : Defines the entry point for the console application.
// // 《剑指Offer——名企面试官精讲典型编程题》代码
// 著作权所有者:何海涛 #include "stdafx.h"
#include "..\Utilities\BinaryTree.h"
#include <exception> BinaryTreeNode* ConstructCore(int* startPreorder, int* endPreorder, int* startInorder, int* endInorder); BinaryTreeNode* Construct(int* preorder, int* inorder, int length)
{
if(preorder == NULL || inorder == NULL || length <= )
return NULL; return ConstructCore(preorder, preorder + length - ,
inorder, inorder + length - );
} BinaryTreeNode* ConstructCore
(
int* startPreorder, int* endPreorder,
int* startInorder, int* endInorder
)
{
// 前序遍历序列的第一个数字是根结点的值
int rootValue = startPreorder[];
BinaryTreeNode* root = new BinaryTreeNode();
root->m_nValue = rootValue;
root->m_pLeft = root->m_pRight = NULL; if(startPreorder == endPreorder)
{
if(startInorder == endInorder && *startPreorder == *startInorder)
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 > )
{
// 构建左子树
root->m_pLeft = ConstructCore(startPreorder + , leftPreorderEnd,
startInorder, rootInorder - );
}
if(leftLength < endPreorder - startPreorder)
{
// 构建右子树
root->m_pRight = ConstructCore(leftPreorderEnd + , endPreorder,
rootInorder + , endInorder);
} return root;
} // ====================测试代码====================
void Test(char* testName, int* preorder, int* inorder, int length)
{
if(testName != NULL)
printf("%s begins:\n", testName); printf("The preorder sequence is: ");
for(int i = ; i < length; ++ i)
printf("%d ", preorder[i]);
printf("\n"); printf("The inorder sequence is: ");
for(int i = ; i < length; ++ i)
printf("%d ", inorder[i]);
printf("\n"); try
{
BinaryTreeNode* root = Construct(preorder, inorder, length);
PrintTree(root); DestroyTree(root);
}
catch(std::exception& exception)
{
printf("Invalid Input.\n");
}
} // 普通二叉树
// 1
// / \
// 2 3
// / / \
// 4 5 6
// \ /
// 7 8
void Test1()
{
const int length = ;
int preorder[length] = {, , , , , , , };
int inorder[length] = {, , , , , , , }; Test("Test1", preorder, inorder, length);
} // 所有结点都没有右子结点
// 1
// /
// 2
// /
// 3
// /
// 4
// /
//
void Test2()
{
const int length = ;
int preorder[length] = {, , , , };
int inorder[length] = {, , , , }; Test("Test2", preorder, inorder, length);
} // 所有结点都没有左子结点
// 1
// \
// 2
// \
// 3
// \
// 4
// \
// 5
void Test3()
{
const int length = ;
int preorder[length] = {, , , , };
int inorder[length] = {, , , , }; Test("Test3", preorder, inorder, length);
} // 树中只有一个结点
void Test4()
{
const int length = ;
int preorder[length] = {};
int inorder[length] = {}; Test("Test4", preorder, inorder, length);
} // 完全二叉树
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
void Test5()
{
const int length = ;
int preorder[length] = {, , , , , , };
int inorder[length] = {, , , , , , }; Test("Test5", preorder, inorder, length);
} // 输入空指针
void Test6()
{
Test("Test6", NULL, NULL, );
} // 输入的两个序列不匹配
void Test7()
{
const int length = ;
int preorder[length] = {, , , , , , };
int inorder[length] = {, , , , , , }; Test("Test7: for unmatched input", preorder, inorder, length);
} int _tmain(int argc, _TCHAR* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7(); return ;
}
5. targetver.h (Utilities/ 目录)
#pragma once // The following macros define the minimum required platform. The minimum required platform
// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run
// your application. The macros work by enabling all features available on platform versions up to and
// including the version specified. // Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
#ifndef WINVER // Specifies that the minimum required platform is Windows Vista.
#define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif #ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif #ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98.
#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
#endif #ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0.
#define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE.
#endif
6. stdafx.h (Utilities/ 目录)
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
// #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#include <stdio.h> // TODO: reference additional headers your program requires here
7. stdafx.cpp (Utilities/ 目录)
// stdafx.cpp : source file that includes just the standard includes
// Utilities.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H
// and not in this file
8. BinaryTree.h
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 著作权所有者:何海涛 #pragma once struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
}; __declspec( dllexport ) BinaryTreeNode* CreateBinaryTreeNode(int value);
__declspec( dllexport ) void ConnectTreeNodes(BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight);
__declspec( dllexport ) void PrintTreeNode(BinaryTreeNode* pNode);
__declspec( dllexport ) void PrintTree(BinaryTreeNode* pRoot);
__declspec( dllexport ) void DestroyTree(BinaryTreeNode* pRoot);
9. BinaryTree.cpp
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 著作权所有者:何海涛 #include "StdAfx.h"
#include "BinaryTree.h" BinaryTreeNode* CreateBinaryTreeNode(int value)
{
BinaryTreeNode* pNode = new BinaryTreeNode();
pNode->m_nValue = value;
pNode->m_pLeft = NULL;
pNode->m_pRight = NULL; return pNode;
} void ConnectTreeNodes(BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight)
{
if(pParent != NULL)
{
pParent->m_pLeft = pLeft;
pParent->m_pRight = pRight;
}
} void PrintTreeNode(BinaryTreeNode* pNode)
{
if(pNode != NULL)
{
printf("value of this node is: %d\n", pNode->m_nValue); if(pNode->m_pLeft != NULL)
printf("value of its left child is: %d.\n", pNode->m_pLeft->m_nValue);
else
printf("left child is null.\n"); if(pNode->m_pRight != NULL)
printf("value of its right child is: %d.\n", pNode->m_pRight->m_nValue);
else
printf("right child is null.\n");
}
else
{
printf("this node is null.\n");
} printf("\n");
} void PrintTree(BinaryTreeNode* pRoot)
{
PrintTreeNode(pRoot); if(pRoot != NULL)
{
if(pRoot->m_pLeft != NULL)
PrintTree(pRoot->m_pLeft); if(pRoot->m_pRight != NULL)
PrintTree(pRoot->m_pRight);
}
} void DestroyTree(BinaryTreeNode* pRoot)
{
if(pRoot != NULL)
{
BinaryTreeNode* pLeft = pRoot->m_pLeft;
BinaryTreeNode* pRight = pRoot->m_pRight; delete pRoot;
pRoot = NULL; DestroyTree(pLeft);
DestroyTree(pRight);
}
}
10. 参考代码下载
项目 06_ConstructBinaryTree 下载: 百度网盘
何海涛《剑指Offer:名企面试官精讲典型编程题》 所有参考代码下载:百度网盘
参考资料
[1] 何海涛. 剑指 Offer:名企面试官精讲典型编程题 [M]. 北京:电子工业出版社,2012. 53-58.
重建二叉树(C++和Python实现)的更多相关文章
- 用前序和中序重建二叉树 python
程序实现了用二叉树的前序遍历序列和中序遍历序列重建二叉树,代码用python实现. 首先定义二叉树节点的类: class TreeNode: def __init__(self, x): self.v ...
- 【算法编程 C++ Python】根据前序遍历、中序遍历重建二叉树
题目描述 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字.例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7, ...
- 重建二叉树[by Python]
题目: 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字.例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2 ...
- 剑指offer——python【第4题】重建二叉树
题目描述 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字.例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7, ...
- 重建二叉树(python)
题目描述 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字.例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7, ...
- 《剑指offer》重建二叉树
本题来自<剑指offer> 重构二叉树 题目: 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字.例如输入前序遍历序列{1,2 ...
- 剑指Offer 4. 重建二叉树 (二叉树)
题目描述 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字.例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7, ...
- 二叉树题目集合 python
二叉树是被考察频率非常高的数据结构.二叉树是按照“父节点-左子树&右子树”这样的方式,由根节点不断向下扩展,形成一棵树的结构.二叉树经常被提到的三种遍历方式:前序遍历.中序遍历和后序遍历,既是 ...
- 剑指offer4:重建二叉树(后序遍历)
1. 题目描述 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字.例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4 ...
- 剑指Offer(四):重建二叉树
一.前言 刷题平台:牛客网 二.题目 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字.例如输入前序遍历序列{1,2,4,7,3,5,6, ...
随机推荐
- Linux下Python3.5使用pyqt5.11报错 ImportError: /usr/local/lib/python3.5/dist-packages/PyQt5/QtCore.so: undefined symbol: PySlice_AdjustIndices 解决方法
我用的Linux自带的是Python3.5版本,运行pip3 install PyQt5, 下载的是PyQt5.11,运行PyQt5程序会报错: ImportError: /usr/local/lib ...
- mp4 格式无法使用html5的video标签播放
只有视频编码为h264的视频才能在html5中使用video标签播放 我的解决方法为:下载魔影工厂,按照如下图所示步骤操作: width:600px;
- PHP输出毫秒时间戳
代码: <?php list($msec, $sec) = explode(' ', microtime()); $msectime = (float)sprintf('%.0f', (floa ...
- cordova 更改app的图标
写在前面:cordova 使一个前端开发者成为一个“假”的android开发人员,不得不说提供给我们巨大的方便~,cordova打包生成的apk的默认样式和启动的名字真的是需要我们字更改的:本文将记录 ...
- 集合 相关 深浅copy
'' 集合:可变的数据类型,他里面的元素必须是不可变的数据类型,无序,不重复. {} ''' # set1 = set({1,2,3}) # set2 = {1,2,3,[2,3],{'name':' ...
- init_config_file.lua
--[[ 读取限流配置 --]] --获取共享内存 local limit_req_store = ngx.shared.limit_req_store --初始化拒绝 URI 列表 reject_u ...
- MySQL初始化与用户配置
数据库初始化 默认情况下,数据已经初始化好,数据可参见默认配置文件/etc/my.cnf 在其他位置重新初始化MySQL数据库: basedir是mysql的安装根目录,ldata是数据初始化的目录 ...
- MySQL获取字段的片段
如表中有很多这样的数据: TEST-123,TEST-III 这种以 TEST开头的数据,为了统计其总数 可以使用mysql自带的方法 substring_index()方法 第一个参数是列的内容, ...
- TCP/IP协议簇分层详解---转
http://blog.csdn.net/hankscpp/article/details/8611229 一. TCP/IP 和 ISO/OSI ISO/OSI模型,即开放式通信系统互联参考模型(O ...
- Firebird hash join
Firebird 现可支持哈希连接(hash join),各中大型数据库,哈希连接已成为平常,相对于循环嵌套连接(Nested Loop Join),在数据量较大的情况下,哈希连接性能较好. 由于 F ...