• 输出二叉树的所有路径


    #include <stdio.h>
    #include <stdlib.h>
    typedef struct node
    {
      char data;
      node *lchild;
      node *rchild;
    }TreeNode;

    void CreateTree(TreeNode *&Node, char *pstr)
    {
      int top = -1;
      TreeNode *Stack[100];
      char ch = *pstr;
      int j = 0;
      int t;
      TreeNode *p = NULL;
    while(ch != '\0')
    {
      switch(ch)
      {
        case '(':
         Stack[++top] = p;t = 1;
          break;
        case ')':
          top--;
          break;
        case ',':
          t = 2;
          break;
        default:
          p = (TreeNode *)malloc(sizeof(TreeNode));
          p->lchild = p->rchild = NULL;p->data = ch;
        if (Node == NULL)
        {
          Node = p;
        }
        else
        {
          switch(t)
          {
            case 1:
              Stack[top]->lchild = p;
              break;
            case 2:
              Stack[top]->rchild = p;
              break;
            }
          }
          break;
        }
        ch = pstr[++j];
      }
    }

    void AllPath(TreeNode *Node)
    {
      TreeNode *p = Node;
      TreeNode *Stack[100];
      int flag;
      TreeNode *q = NULL;
      int top = -1;
      do
      {
         while(p != NULL)
         {
          Stack[++top] = p;
          p = p->lchild;
         }
         q = NULL;
         flag = 1;
         while(flag && top >= 0)
        {
          p = Stack[top];
          if (q == p->rchild)
          {
            if (p->lchild == NULL && p->rchild == NULL)
            {
              for (int i = 0; i <= top; i++)
              {
                printf("%c", Stack[i]->data);
              }
              printf("\n");
            }
            --top;
            q = p;
          }
          else
          {
            p = p->rchild;
            flag = 0;
          }
        }
      } while (top >= 0);
    }

    int _tmain(int argc, _TCHAR* argv[])
    {
      char str[] = "A(B(D(,G)),C(E,F))";
      TreeNode *Node = NULL;
      CreateTree(Node, str);
      AllPath(Node);
      return 0;
    }

  • 相关阅读:
    Codeforces 1098C Construct a tree
    使用node查询数据库 (mysql) 时间类型字段返回日期格式不对的解决方式 何苦
    vue2中如何使用组合式API和vueuse工具包
    useSlotsTS
    arcodesignprovite项目配置参考
    Flutter配置环境
    Android项目mvvm的尝试
    华为云平台修改/etc/resolv.conf中的域
    Python将函数动态绑定为对象的成员方法
    canal学习之数据同步(一)
  • 原文地址:https://www.cnblogs.com/lzmfywz/p/3011142.html
Copyright © 2020-2023  润新知