zoukankan      html  css  js  c++  java
  • 【leetcode】N叉树的前序遍历

    /*递归*/
    void func(struct Node* root, int* arr,int* returnSize)
    {
        arr[(*returnSize)++] = root->val;
        for (int i=0; i<root->numChildren; i++)
        {
            func(root->children[i],arr,returnSize);
        }
    }
    int* preorder(struct Node* root, int* returnSize) {
        *returnSize=0;
        if (!root) return NULL;
        int* arr = (int*)calloc(10000,sizeof(int));
        func(root,arr,returnSize);
        return arr;
    }
    /**
     * 迭代
     **/ 
    #define MAX_SIZE 10240
    int* preorder(struct Node* root, int* returnSize) {
      int i, top = -1, *result = (int*)calloc(MAX_SIZE, sizeof(int));
      struct Node *p, **stack = (char**)malloc(sizeof(struct Node*) * MAX_SIZE);
      *returnSize = 0;
      if (root == NULL) return result;
      stack[++top] = root;
      while (top != -1) {
        p = stack[top--];
        result[(*returnSize)++] = p->val;
        // 从最后一个孩子开始入栈
        for (i = p->numChildren - 1; i >= 0; i--)
          stack[++top] = p->children[i];
      }
      return result;
    }
  • 相关阅读:
    git
    rocketMq
    mysql 擎特点
    mysql 主从复制实现步骤
    mysql数据库服务日志
    mysql 主命令总结
    linux sed
    学习进步的方法
    my-innodb-heavy-4g.cnf
    FTP主动模式和被动模式的区别【转】
  • 原文地址:https://www.cnblogs.com/ganxiang/p/13674455.html
Copyright © 2011-2022 走看看