求二叉树从叶子到根节点的值组成数字的和

来源:互联网 发布:中国产业安全数据 编辑:程序博客网 时间:2024/06/05 03:12

题目:如下图二叉树,每个叶子节点到根节点的数值可以组成一个数字,如253/753/83,写代码求和,即253+753+83=1089


基本思路:利用栈,后序遍历二叉树,顺便求和,代码如下:

#include <stdio.h>#include <string.h>#include <math.h>#define NUM 5typedef struct node{    int val;    int l;    int r;}tree;typedef struct stack{    int top;    tree s[NUM];}tree_stack;tree_stack s;int is_empty(tree_stack *s){    return (s->top == -1);}int is_full(tree_stack *s){    return (s->top >= NUM);}int push(tree_stack *s, tree *n){    if(is_full(s))        return -1;    s->top++;    memcpy(s->s + s->top, n, sizeof(tree));    return 0;}int pop(tree_stack *s, tree *n){    if(is_empty(s) || !n)        return -1;    memcpy(n, s->s + s->top, sizeof(tree));    s->top--;        return 0;}void init_tree(tree *t){    t[0].val = 3;    t[0].l = 1;    t[0].r = 2;        t[1].val = 5;    t[1].l = 3;    t[1].r = 4;        t[2].val = 8;    t[2].l = -1;    t[2].r = -1;            t[3].val = 2;    t[3].l = -1;    t[3].r = -1;        t[4].val = 7;    t[4].l = -1;    t[4].r = -1;}int calcute(tree_stack *s){    tree n;    int val,i;    pop(s,&n);    val = 0;    if(n.l==-1 && n.r == -1)    {        val = n.val * pow(10,s->top+1);        for(i=s->top;i>=0;i--)        {            val += s->s[i].val * pow(10,i);        }        printf("val:%d\n",val);    }    return val;}void show_tree(tree *t, int index, int *total){    if(index < 0)        return;    push(&s,t+index);    show_tree(t,t[index].l,total);    show_tree(t,t[index].r,total);    *total += calcute(&s);}int main(){    int total = 0;    tree t[NUM];    s.top = -1;    init_tree(t);    show_tree(t,0, &total);    printf("total:%d\n",total);    return 0;}




阅读全文
0 0