leetcode Minimum Depth of Binary Tree

题目:返回根节点到最近的叶子节点的距离。

例如:{1,2},其中2是1的左子树,1的右子树为空,2为叶子节点,那么此时返回2.

如果用简单的递归,以为是返回左右两边的最小值加1,那么上面那个case就错了,因为如果返回左右两边最小值加1的话,上面1的右边是0,所以返回1,但我们想要的是2.

所以要另外注意递归的返回条件。

也就是如果是叶节点了那就返回1,不为空的时候才递归,详见代码:

/**
 * 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) return 0;
        if (!root -> left && !root -> right) return 1;
        int lf = INT_MAX, ri = INT_MAX;
        if (root -> left)
            lf = minDepth(root -> left);
        if (root -> right)
            ri = minDepth(root -> right);
        return min(lf, ri) + 1;
    }
};

 或者是:

/**
 * 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)return 0;
        int a=minDepth(root->right);
        int b=minDepth(root->left);
        if(a*b!=0)return min(a,b)+1;
        else if(b==0)return a+1;
        else if(a==0) return b+1;
    }
};

 同时记录一下非递归的解法:

public int minDepth(TreeNode root) {
        if(root == null)
            return 0;
        
        int depth = 1;//The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        int curnum = 1;
        int nextnum = 0;
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            curnum--;
            
            if(cur.left == null && cur.right == null)
                return depth;
            
            if(cur.left != null){
               queue.add(cur.left);
               nextnum++;
            }
            
            if(cur.right != null){
                queue.add(cur.right);
                nextnum++;
            }
            
            if(curnum == 0){
                curnum = nextnum;
                nextnum = 0;
                depth++;
            }
        }
        return depth;
    }

 

posted on 2014-11-30 00:07  higerzhang  阅读(212)  评论(0编辑  收藏  举报