leetcode Minimum Depth of Binary Tree

2015-07-20 17:13:13 ? 作者: ? 浏览: 3

?

求二叉树的最小深度。

先看看如何求二叉树的深度:

?

int GetDepth(BinaryTreeNode * pRoot)
{
	if(pRoot == NULL) // 递归出口
		return 0;
	int depthLeft = GetDepth(pRoot->m_pLeft);
	int depthRight = GetDepth(pRoot->m_pRight);
	return depthLeft > depthRight ? (depthLeft + 1) : (depthRight + 1); 
}

这里有一个详细的有关二叉树的算法总结

?

http://blog.csdn.net/luckyxiaoqiang/article/details/7518888

左右子树有一个深度为0的数特殊情况。如果为0,那么树的最小深度是另一个子树的深度加1而不是0+1。

?

?

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
  		    public static int minDepth(TreeNode root) {
		        if(root==null)return 0;
		        if(root.left==null&&root.right==null)return 1;
		        int left=minDepth(root.left);
		        int right=minDepth(root.right);
		        if(left==0)return right+1;
		        if(right==0)return left+1;
		        return (left
  
   还有一个求最深深度的问题

https://oj.leetcode.com/submissions/detail/17722350/
   

?

?

public class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null)return 0;
        if(root.left==null&&root.right==null)return 1;
        int left=maxDepth(root.left);
        int right=maxDepth(root.right);
        return Math.max(left,right)+1;
    }
}


?

-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: