3.2 94. Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of 
its nodes' values.

For example:
Given binary tree [1,null,2,3],
   1
    \
     2
    /
   3
return [1,3,2].

中序的走法,是左->中->右

/**
 * 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().
 */

 void inorder_traversal(struct TreeNode* n,int array[], int *i)
{

    if(n!=NULL){
        inorder_traversal(n->left,array,i);
        array[(*i)]=n->val;
        (*i)++;
        inorder_traversal(n->right,array,i);
    }
}


int* inorderTraversal(struct TreeNode* root, int* returnSize) {
    int *nodes;
     int array[1000];
     int i=0;

     if(root ==NULL)
        return 0;


     inorder_traversal(root,array,&i);


     *returnSize=i;
     nodes=(int *)malloc(i*sizeof int);
     memcpy(nodes,array,i*sizeof int);

     return nodes;

}

results matching ""

    No results matching ""