Tuesday, October 7, 2014

Minimum Depth of Binary Tree

two methods:1)recursion. 2) use queue, level order traverse
//from anniekim
    int minDepth(TreeNode *root) {
        if(!root) return 0;
        if(!root->left)
            return 1+minDepth(root->right);
        if(!root->right)
            return 1+minDepth(root->left);
        return 1+min(minDepth(root->left),minDepth(root->right));
    }

    int minDepth(TreeNode *root) {
        if (!root) return 0;
        queue<TreeNode *> q;
        q.push(root);
        q.push(NULL);
        int depth = 1;
        while (true)
        {
            TreeNode *node = q.front();
            q.pop();
            if (!node) {
                depth++;
                q.push(NULL);
            } else {
                if (!node->left && !node->right) return depth;
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }
        }
    }



// another flavor of using queue

int minDepth(TreeNode *root) {
    if(!root)
        return 0;
    queue<TreeNode*> aQueue;
    aQueue.push(root);
    int curdep=1;
    int curlevel=1;
    int nexlevel=0;
    while(!aQueue.empty())
    {
        TreeNode*pointer=aQueue.front();
        aQueue.pop();
        curlevel--;
        if(pointer->left==NULL&&pointer->right==NULL)
            return curdep;
        if(pointer->left)
            {aQueue.push(pointer->left);nexlevel++;}
        if(pointer->right)
            {aQueue.push(pointer->right);nexlevel++;}
        if(curlevel==0) 
            {curdep++;swap(curlevel,nexlevel);    }
    }
}
int minDepth(TreeNode *root) {
    if (!root) return 0;
    queue<TreeNode *> q;
    q.push(root);
    TreeNode * rightmost = root;
    int depth = 1;
    while (!q.empty())
    {
        TreeNode *node = q.front();
        q.pop();
        if (!node->left && !node->right) return depth;
        if (node->left) q.push(node->left);
        if (node->right) q.push(node->right);
        if (node == rightmost) {
            ++depth;
            rightmost = node->right?node->right:node->left;
        }
    }
}

No comments:

Post a Comment