前言
二叉树是数据结构中最基础也最重要的结构之一。在实际开发或面试中,我们经常遇到两个经典问题:如何根据遍历序列还原树的结构,以及如何判断一棵树是否满足完全二叉树的性质。下面结合 C++ 代码,聊聊这两个问题的核心思路。
从前序和中序遍历重建二叉树
给定前序遍历(Preorder)和中序遍历(Inorder)序列,我们可以唯一确定一棵二叉树。关键在于前序遍历的第一个元素一定是根节点。找到这个根节点在中序遍历中的位置后,左边就是左子树,右边是右子树。通过递归处理左右区间,就能完成整棵树的构建。
实现时需要注意索引的传递,避免重复计算。下面是具体的 C++ 实现:
#include <iostream>
#include <vector>
struct BinaryTreeNode {
int value;
BinaryTreeNode* left;
BinaryTreeNode* right;
BinaryTreeNode(int x) : value(x), left(nullptr), right(nullptr) {}
};
// 递归构建函数
BinaryTreeNode* buildTree(const std::vector<int>& preorder, const std::vector<int>& inorder, int& preIndex, int inStart, int inEnd) {
if (inStart > inEnd) return nullptr;
BinaryTreeNode* root = new BinaryTreeNode(preorder[preIndex++]);
int inIndex = -1;
// 在中序遍历中寻找根节点位置
for (int i = inStart; i <= inEnd; ++i) {
if (inorder[i] == root->value) {
inIndex = i;
break;
}
}
root->left = buildTree(preorder, inorder, preIndex, inStart, inIndex - );
root->right = (preorder, inorder, preIndex, inIndex + , inEnd);
root;
}
{
preIndex = ;
(preorder, inorder, preIndex, , <>(inorder.()) - );
}
{
(node == ) ;
(node->left);
std::cout << node->value << ;
(node->right);
}

