第一次动手写二叉树的,有点小激动,64行的if花了点时间,上传leetcode一次点亮~~~

 /* inorder traversal binary tree */
#include <stdio.h>
#include <stdlib.h> struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
}; int* inorderTraversal(struct TreeNode* root, int* returnSize); int main() { struct TreeNode n1, n2, n3;
n1.val = 1;
n1.left = NULL;
n1.right = &n2;
/* */
n2.val = 2;
n2.left = &n3;
n2.right = NULL;
/* */
n3.val = 3;
n3.left = NULL;
n3.right = NULL;
int returnSize = 0;
int *a = inorderTraversal(&n1, &returnSize); int i=0;
for(i=0; i<returnSize; i++)
printf("%d ", a[i]); printf("\n"); } /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* inorderTraversal(struct TreeNode* root, int* returnSize) { struct TreeNode **stack = (struct TreeNode **) malloc (sizeof(struct TreeNode *) * 1000); /* store node not access at present */
int *result = (int *) malloc(sizeof(int) * 1000);
int count = 0;
stack[0] = root; /* first node */
struct TreeNode* curr;
int top = 0; /* element number in stack */ while(top != -1 ) {
curr = stack[top]; /* get stack top element */ if(curr == NULL) { /* if current element is null */
while(top != -1 && curr == NULL)
curr = stack[--top];
if(top == -1 || curr == NULL)
break;
else {
result[count++] = curr->val;
stack[top] = curr->right;
continue;
}
}
if(curr->left != NULL)
stack[++top] = curr->left; if(curr->left == NULL) { /* if left subtree is NULL, then we need to access middle node */
result[count++] = curr->val;
stack[top] = curr->right;
}
}
*returnSize = count;
return result;
}

最新文章

  1. 利用nagios搭建打印机监控服务器
  2. Android 数据传递(二)Activity与fragment之间的通信
  3. 关于Google+以及Facebook第三方登录实现的一点总结
  4. 【SQL学习笔记】排名开窗函数,聚合开窗函数(Over by)
  5. ASP.NET Core:部署项目到Ubuntu Server
  6. Python的join()函数和split()函数
  7. jav音频格式转换 ffmpeg 微信录音amr转mp3
  8. JVM工具jstat使用说明
  9. 剑指Offer 33. 丑数 (其他)
  10. [APM] 2个实例+5个维度解读APM技术
  11. Spring学习笔记--Spring简介
  12. [Spark]Spark章1 Spark架构浅析
  13. HTML and CSS学习概述
  14. Python3在指定路径下递归定位文件中出现的字符串
  15. Start Developing iOS Apps (Swift) 开始开发iOS应用(Swift)
  16. OpenGL 多线程共享纹理
  17. HDU 2199 (二分法)
  18. 趣味js【练习题】
  19. SPI子系统分析之一:框架
  20. redis info命令中各个参数的含义

热门文章

  1. BZOJ 2330 [SCOI2011]糖果 ——差分约束系统 SPFA
  2. BZOJ1875 [SDOI2009]HH去散步 【dp + 矩阵优化】
  3. oracle distinct 用法
  4. 2-sat 问题 【例题 Flags(2-sat+线段树优化建图)】
  5. OpenStack 通用设计思路
  6. Yii使用find findAll查找出指定字段的实现方法
  7. JS-日历签到
  8. HDU 5988最小网络流(浮点数)
  9. Go -- LFU类(缓存淘汰算法)(转)
  10. BEGINNING SHAREPOINT&amp;#174; 2013 DEVELOPMENT 第2章节--SharePoint 2013 App 模型概览 SharePoint 2013 App 模型