您的位置:首页 > 其它

leetcode-111 Minimum Depth of Binary Tree

2015-04-06 15:44 295 查看
这题和104Maximum Depth of Binary Tree不一样,递归的时候不能直接返回min(left,right)+1

<span style="font-size:14px;">/**
 * 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;
        int left = minDepth(root->left);
        int right = minDepth(root->right);
        return (left == 0 || right == 0) ? left+right+1:min(left,right)+1;
    }
};</span>


或者:

<span style="font-size:14px;">class Solution {
public:
    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));
    }
};</span>


以上两种方法都是DFS(深度优先遍历),也可以采用广度优先遍历(BFS),当某个结点没有孩子节点时,就结束,当前的层数为树的最小深度

<span style="font-size:14px;">/**
 * 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;
        int level = 0;
        queue<TreeNode *> btn;
        btn.push(root);
        while(!btn.empty()){
           level++;
           for(int i = 0,n = btn.size(); i < n; i++){
               TreeNode *tmp = btn.front();
               btn.pop();
               if(!tmp->left && !tmp->right) return level;//某个节点没有孩子,则必为叶子节点
               if(tmp->left) btn.push(tmp->left);
               if(tmp->right) btn.push(tmp->right);
           }
        }
    }
};</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: