Saturday, April 11, 2015

Minimum Depth of Binary Tree

Problem:
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.



Solution:
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode *root) {
        if (root == NULL)
            return 0;
        else if (root -> left == NULL && root -> right == NULL)
            return 1;
        else if (root -> left == NULL)
            return minDepth(root -> right) + 1;
        else if (root -> right == NULL)
            return minDepth(root -> left) + 1;
        else
            return min(minDepth(root -> left), minDepth(root -> right)) + 1;
    }
};

======= BFS approach ==== (Use of pair<node *, depth>)
class Solution {
public:
    int minDepth(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        queue< pair<TreeNode*,int> > q;
        int i=0;
        if (!root){return 0;}
        q.push(make_pair(root,1));
        while(!q.empty()){
            pair<TreeNode*,int> cur = q.front();
            q.pop();
            if (!cur.first->left && !cur.first->right){
                return cur.second;
            }
            if(cur.first->left){
                q.push(make_pair(cur.first->left,cur.second+1));
            }
            if(cur.first->right){
                q.push(make_pair(cur.first->right,cur.second+1));
            }
        }
    }
};

No comments:

Post a Comment