leetcode之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.

思路:该题的本质就是一个先序遍历,但在遍历时应该返回左右子树的最小长度,所以在初始时应将minCount设为较大的一个数。另外,叶节点的判断是左右子树都为空,所以切记递归结束条件的判断。另外还是要深刻理解递归算法,包括先序遍历,中序遍历和后序遍历。

 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 minCount = 65535;
		int count = 1;
		 return countDepth(root,count,minCount);
    }
	int countDepth(TreeNode *root,int count,int minCount){
		if(root->left == NULL && root->right == NULL ){
			if(count < minCount)
				minCount = count;
			return minCount;
		}
		int count1 = 65535 ,count2 = 65535;
		if(root->left !=NULL)
	           count1 = countDepth(root->left,count + 1,minCount);
		if(root->right != NULL)
	           count2 = countDepth(root->right,count + 1,minCount);
		return count1 < count2 ? count1:count2;
		
	}
};

PS(2014.10.09):今天复习此题,发现上述代码思路不够简洁,优化后的代码如下:

int minDepth(TreeNode *root) {
        if(root == NULL)
            return 0;
        if(root->left == NULL && root->right == NULL)
            return 1;
        int d1= 65535,d2 = 65535;
        if(root->left != NULL)
            d1 = minDepth(root->left) +1;
        if(root->right != NULL)
            d2 = minDepth(root->right) +1;
        return d1< d2?d1:d2;
        
        
    }
    



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值