[Leetcode] The minimum depth of binary tree二叉树的最小深度

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.

方法一:

层次遍历。主体的思想不变,程序的主体结构也不变,具体遍历过程参照二叉树的层次遍历。关键在于终止条件,在某一层中,节点遍历的顺序是从左往右的,若是最短路径出现在该层中,则其中一定有某一节点的左、右孩子均不存在,即为叶节点。返回level+1是因为最小的深度要算该节点所在的层。

class Solution {
public:
    int run(TreeNode *root) 
    {
        if(root==NULL)  return 0;
        int level=0;
        queue<TreeNode *> Q;
        Q.push(root);
        while( !Q.empty())
        {
            int levNum=0;
            int count=Q.size();

            while(levNum<count)
            {
                TreeNode *temp=Q.front();
                Q.pop();
                if(temp->left==NULL&&temp->right==NULL)
                    return level+1;
                if(temp->left)
                    Q.push(temp->left);
                if(temp->right)
                    Q.push(temp->right);
            
                levNum++;
            }
            level++;
        }  
        return level;     
    }
};

 

方法二:

思想还是层次遍历,写法不一样。make_pair中第一元素为节点,第二个元素为改节点所在的层数。即让每个进入队列中的节点都携带所在层数信息。非本人原创

class Solution {
public:
    int run(TreeNode *root) 
    {
        queue<pair<TreeNode *,int>> Q;
        if(root==NULL)  return 0;
        Q.push(make_pair(root,1));

        while(!Q.empty())
        {
            pair<TreeNode *,int> cur=Q.front();
            Q.pop();
            if(cur.first->left==NULL&&cur.first->right==NULL)
                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));
        }
        return 0;
    }
};

 

方法三:

递归算法,参见Grandyang

class Solution {
public:
    int minDepth(TreeNode *root) {
        if (root == NULL) return 0;
        if (root->left == NULL && root->right == NULL) return 1;
        
        if (root->left == NULL) return minDepth(root->right) + 1;
        else if (root->right == NULL) return minDepth(root->left) + 1;
        else return 1 + min(minDepth(root->left), minDepth(root->right));
    }
    
};

递归的另一种写法:@牛客网友

class Solution {
public:
    int run(TreeNode *root) 
    {
        if(root==NULL)  return 0;
        
        int lChild=run(root->left);
        int rChild=run(root->right);

        if(lChild==0||rChild==0)
            return 1+lChild+rChild;
        return 1+min(lChild+rChild);
    }
};

 

posted @ 2017-06-10 16:46  王大咩的图书馆  阅读(323)  评论(0编辑  收藏  举报