文章
454
粉丝
0
获赞
1
访问
10.2k
多棵一般树,每棵用一串 'd'/'u' 描述:'d' 表示进入当前结点的子结点,'u' 表示退回父结点,最后一行以 '#' 结束。对每棵树输出「Tree t: h1 => h2」,h1 是原树的高度、h2 是把它转成「左儿子右兄弟」二叉树后的高度(根的高度记 0)。
边模拟边建二叉树:读 'd' 时新建结点,若父结点还没有孩子就挂成左儿子,否则挂成父结点上一个孩子的右兄弟。
h1 就是模拟时栈的最大深度减一。
h2 用迭代 DFS 求二叉树最大深度再减一;深链可能长达上万层,递归容易爆栈。
O(L),L 为串长。
C:
#include <stdio.h>
#include <string.h>
static int leftc[20005], rightc[20005], lastc[20005];
static int stk[20005];
static int depthBt(int u) {
int a = 0, b = 0;
if (leftc[u] >= 0) a = depthBt(leftc[u]);
if (rightc[u] >= 0) b = depthBt(rightc[u]);
return 1 + (a > b ? a : b);
}
int main(void) {
char s[20005];
int t = 0;
while (scanf("%20000s", s) == 1) {
if (s[0] == '#') break;
t++;
{
int i, nodes = 1, top = 1, maxd = 1;
for (i = 0; i < 20005; i++) { leftc[i] = rightc[i] = lastc[i] = -1; }
stk[0] = 0;
for (i = 0; s[i]; i++) {
if (s[i] == 'd') {
...
登录后发布评论
暂无评论,来抢沙发