重建二叉树(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, ...
随机推荐
- Python——数据交换格式简要
简单数据交换格式 CSV: 一般用 open() 函数和字符串拆分 split() 方法,但python有内置的csv模块 读: import csv with open(r"C:\ ...
- c# 水晶报表使用说明
水晶报表介绍 水晶报表是 vs 早期版本自带的一款报表控件.vs2017不自带水晶报表,需要自行安装.虽然水晶报表是收费控件,但是微软已经付过钱了,所以vs自带的水晶报表可以直接使用. 如果项目是 . ...
- proxy的作用
get() get方法用于拦截某个属性的读取操作,可以接受三个参数,依次为目标对象.属性名和 proxy 实例本身(严格地说,是操作行为所针对的对象),其中最后一个参数可选. get方法的用法,上文已 ...
- 给你的移动网站加点料:推荐下载App,如果本地安装则直接打开本地App(Android/IOS)
纵观现在每家移动网站,打开首页的时候,都有各种各样的形式来提示你下载自身的移动App(Android/IOS),这是做移动客户端产品的一个很好地引流的手段.当然各家引流下载的交互和视觉各不相同,有的是 ...
- Ajax(Asychronous JavaScript and XML)笔记
1 Ajax简介 1 ajax概念 2 什么是同步?什么是异步? 3 ajax原理 2 JavaScript原生的ajax 1 ajax.html代码 <!DOCTYPE html> &l ...
- 关于ie8兼容性问题的处理
1.replace将单引号变成双引号 var page=user.customConfig.replace(/\‘|’/ig,"\""); 兼容谷歌和ie var pag ...
- 【Docker】制作一个支持SSH终端登录的镜像
首先从官方或者docker.cn的镜像库中pull下来ubuntu镜像: docker pull ubuntu 现在用命令查看一下pull下来的ubuntu镜像: docker images 关于如何 ...
- first post
post
- 三:Mybatis知识整理(3)
一:mybatis中模糊查询的方法: 1.直接传参法:在java传参时进行拼接 -- %keyword% 2.mysql内置函数:concart('%',#{keyword},'%') -- 拼接sq ...
- Java--详解WebService技术
Java--详解WebService技术 一.什么是 webservice WebService是一种跨编程语言和跨操作系统平台的远程调用技术. 所谓跨编程语言和跨操作平台,就是说服务端程序采用jav ...