基于二叉链表的二叉树叶子结点到根结点的路径的求解
#include<iostream>
#include<vector>
using namespace std;
typedef struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode() :val('0'), left(nullptr), right(nullptr) {
}
TreeNode(char x) :val(x), left(nullptr), right(nullptr) {
}
}TreeNode, * BiTree;
BiTree PreInsert() {
char x;
cin >> x;
if (x == '0') return nullptr;
TreeNode* root = new TreeNode(x);
root->left = PreInsert();
root->right = PreInsert();
return root;
}
//vector版本
void findAllPathInBinaryTree(BiTree T,vector<char>v) {
if (T == nullptr) return;
//加入当前结点到路径中
v.push_back(T->val);
if (T->left == nullptr && T->right == nullptr) {
//当前为叶子结点
//输出路径
/* for (auto i : v) {
cout << i;
}*/
//倒序输出
for (int i = v.size() - 1; i >= 0; i--) {
cout << v[i];
}
cout << endl;
return;
}
//非叶子节点
//遍历下一结点,并传递路径
findAllPathInBinaryTree(T->left, v);
findAllPathInBinaryTree(T->right, v);
}
//数组版本
void findAllPathInBinaryTree1(BiTree T, char v[],int i) {
if (T == nullptr) return;
//加入当前结点到路径中
v[i] = T->val;
if (T->left == nullptr && T->right == nullptr) {
//当前为叶子结点
//输出路径
/* for (auto i : v) {
cout << i;
}*/
//倒序输出
for (int j = i; j >= 0; j--) {
cout << v[j];
}
cout << endl;
return;
}
//非叶子节点
//遍历下一结点,并传递路径
findAllPathInBinaryTree1(T->left, v,i+1);
findAllPathInBinaryTree1(T->right, v,i+1);
}
int main() {
BiTree T;
while (true) {
T = PreInsert();
if (T == nullptr) break;
/*vector<char>v;
findAllPathInBinaryTree(T,v);*/
char v[100];
findAllPathInBinaryTree1(T, v, 0);
}
return 0;
}