Binary Tree Inorder Traversal


  • 0
    S

    i'm wondering why my code is wrong and i'm so curiously about it, is anyone can give me some tips?

    class Solution:
    # @param {TreeNode} root
    # @return {integer[]}
    integer=[]
    def inorderTraversal(self, root):
    if root:
    self.inorderTraversal(root.left)
    self.integer.append(root.val)
    self.inorderTraversal(root.right)
    return self.integer


  • 0
    K

    shows as wrong answer for case where only root node exists, I have tried the same code on my local machine and it works just fine. not sure what is being expected here!! can someone please help !!

    int* inorderTraversal(struct TreeNode* root, int* returnSize) {
        
        if(root == NULL)
            return NULL;
        
        if(*returnSize <= 0)
            return NULL;
        
        int *arr = (int *)malloc(sizeof(int)*(*returnSize));
        if(arr == NULL)
            return NULL;
        int idx = 0;
        
        struct TreeNode *curr, *pre;
    
        curr = root;
        
        while(curr != NULL)
        {
            if(curr->left == NULL)
            {
                
                arr[idx] = curr->val;
                idx++;
                curr = curr->right;
            }
            else
            {
                pre = curr->left;
                while(pre->right != NULL && pre->right != curr)
                    pre = pre->right;
                
                if(pre->right == NULL)
                {
                    pre->right = curr;
                    curr = curr->left;
                }
                else
                {
                    arr[idx] = curr->val;
                    idx++;
                    curr = curr->right;
                }
            }
        }
        return arr;
        
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.