前言
这种解法只存在实际里,理论上这种问题是无解的
原因在于叶节点的数量会是指数,是不可能在多项式式时间内解完
只要树足够大,这问题就无解
原理
建树——》先序找根——》中序确认左右,递归即可
确认深度——先序遍历即可
代码
主函数建树部分
#include<bits/stdc++.h>
using namespace std;
typedef struct node {
int key;
struct node* lchild, * rchild;
node(int x) {
key = x;
lchild = rchild = NULL;
}
}Tree;
vector<int>preorder{ 1,2,3,4,5,6,7,8,9 };
vector<int>inorder{ 5,4,3,2,7,6,1,9,8 };
int quantity = preorder.size();
Tree* BuildTree(Tree*, int, int, int, int);
void PrintInorder(Tree*);
void PrintLevel(Tree*);
void PrintDepth(Tree*, int);
void PrintNode(Tree*, vector<int>);
int main() {
Tree* root = NULL;
root = BuildTree(root, 0, quantity - 1, 0, quantity - 1);
auto count{ 0 };
PrintDepth(root, count);
printf("\n");
vector<int>visit;
PrintNode(root, visit);
return 0;
}
Tree* BuildTree(Tree* root, int pre_begin, int pre_end, int in_begin, int in_end) {
if (pre_begin - pre_end > 0) {
return root;
}
int w = find(inorder.begin(), inorder.begin() + quantity - 1, preorder[pre_begin]) - inorder.begin();
root = new Tree(preorder[pre_begin]);
int p = w - in_begin;
int q = in_end - w;
root->rchild = BuildTree(root->rchild, pre_end - q + 1, pre_end, w + 1, in_end);//右边
root->lchild = BuildTree(root->lchild, pre_begin + 1, pre_begin + p, in_begin, w - 1);//左边
return root;
}
打印深度模块
void PrintDepth(Tree* T, int high) {
if (T->lchild == NULL && T->rchild == NULL) {
printf("%d\n", high);
return;
}
(high)++;
if (T->lchild != NULL)
PrintDepth(T->lchild, high);
if (T->rchild != NULL)
PrintDepth(T->rchild, high);
}
打印根到叶节点的全部路径
void PrintNode(Tree* T, vector<int>visit) {
visit.push_back(T->key);
if (T->lchild == NULL && T->rchild == NULL) {
for (auto i : visit) printf("%d ", i);
printf("\n");
return;
}
if (T->lchild != NULL)
PrintNode(T->lchild, visit);
if (T->rchild != NULL)
PrintNode(T->rchild, visit);
}