有一棵二叉树,输出从根节点到叶子结点F的路径,并求出叶子结点所在的层次。
思路
用括号表达式来建立二叉树
建立过程:
遇到 '(' 则将前一个节点入栈
遇到 ')' 则将栈顶pop
遇到 ‘,’ 则将该节点得准备得儿子节点由左转到右 //我用一个数组标记
代码
#include <bits/stdc++.h>
using namespace std;
struct node
{
char ch;
int lch, rch;
};
node tree[1000];
string s;
int idx = 0;
int head[1000];
void creat()
{
stack<int> sta;
sta.push(1);
for (int i = 0; i < s.size(); i++) //遍历括号序列
{
int id = sta.top();
if (s[i] <= 'Z' && s[i] >= 'A') //是字符就插入栈顶得id 得lch 或者 rch
{
tree[++idx].ch = s[i]; //新节点
if (head[id]) //判断是左还是右父节点->儿子
tree[id].rch = idx;
else
tree[id].lch = idx;
if (s[i + 1] == '(') //左括号入栈
{
sta.push(idx);
i++;
}
}
else if (s[i] == ')') //右括号出栈
{
sta.pop();
}
else if (s[i] == ',') //遇到','lch 变成 rch
{
head[id]++;
}
}
}
void out(int id) //输出二叉树
{
cout << tree[id].ch;
int f = 0;
if (tree[id].lch)
{
if (!f)
cout << '(';
f = 1;
out(tree[id].lch);
cout << ",";
}
if (tree[id].rch)
{
if (!f)
cout << "(,";
f = 1;
out(tree[id].rch);
}
if (f)
cout << ')';
}
int ff = 0;
void find(char ch, int id)
{
if (ff)
cout << "->";
ff = 1;
cout << tree[id].ch;
if (tree[id].ch == ch)
return;
if (tree[id].lch)
find(ch, tree[id].lch);
if (tree[id].rch)
find(ch, tree[id].rch);
}
void dfs(int num, int id)
{
cout << tree[id].ch << "深度为: " << num << endl;
if (tree[id].lch)
dfs(num + 1, tree[id].lch);
if (tree[id].rch)
dfs(num + 1, tree[id].rch);
}
int main()
{
cin >> s; // A(B(,O),C(F,K))
creat();
cout << "建立得二叉树用括号表达式表示" << endl;
out(1);
cout << endl;
find('K', 1);
cout << endl;
dfs(1, 1);
}
运行结果
//输入:A(B(,O),C(F,K))