第一次动手写二叉树的,有点小激动,64行的if花了点时间,上传leetcode一次点亮~~~
1 /* inorder traversal binary tree */ 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 6 struct TreeNode { 7 int val; 8 struct TreeNode *left; 9 struct TreeNode *right; 10 }; 11 12 int* inorderTraversal(struct TreeNode* root, int* returnSize); 13 14 int main() { 15 16 struct TreeNode n1, n2, n3; 17 n1.val = 1; 18 n1.left = NULL; 19 n1.right = &n2; 20 /* */ 21 n2.val = 2; 22 n2.left = &n3; 23 n2.right = NULL; 24 /* */ 25 n3.val = 3; 26 n3.left = NULL; 27 n3.right = NULL; 28 int returnSize = 0; 29 int *a = inorderTraversal(&n1, &returnSize); 30 31 int i=0; 32 for(i=0; i<returnSize; i++) 33 printf("%d ", a[i]); 34 35 printf("\n"); 36 37 } 38 39 40 /** 41 * Definition for a binary tree node. 42 * struct TreeNode { 43 * int val; 44 * struct TreeNode *left; 45 * struct TreeNode *right; 46 * }; 47 */ 48 /** 49 * Return an array of size *returnSize. 50 * Note: The returned array must be malloced, assume caller calls free(). 51 */ 52 int* inorderTraversal(struct TreeNode* root, int* returnSize) { 53 54 struct TreeNode **stack = (struct TreeNode **) malloc (sizeof(struct TreeNode *) * 1000); /* store node not access at present */ 55 int *result = (int *) malloc(sizeof(int) * 1000); 56 int count = 0; 57 stack[0] = root; /* first node */ 58 struct TreeNode* curr; 59 int top = 0; /* element number in stack */ 60 61 while(top != -1 ) { 62 curr = stack[top]; /* get stack top element */ 63 64 if(curr == NULL) { /* if current element is null */ 65 while(top != -1 && curr == NULL) 66 curr = stack[--top]; 67 if(top == -1 || curr == NULL) 68 break; 69 else { 70 result[count++] = curr->val; 71 stack[top] = curr->right; 72 continue; 73 } 74 } 75 if(curr->left != NULL) 76 stack[++top] = curr->left; 77 78 if(curr->left == NULL) { /* if left subtree is NULL, then we need to access middle node */ 79 result[count++] = curr->val; 80 stack[top] = curr->right; 81 } 82 } 83 *returnSize = count; 84 return result; 85 }
时间: 2024-10-09 04:17:09