maximum-depth-of-binary-tree&&minimum-depth-of-binary-tree

关于二叉树,目前在leetcode中遇到了两道题目,一道是二叉树的最大深度,一道是二叉树的最小深度;关于二叉树,整好借此机会再学习一下;

二叉树是一种特殊的树,在二叉树中每个节点最多有两个子节点,一般称为左子节点和右子节点(或左孩子和右孩子),并且二叉树的子树有左右之分,其次序不能任意颠倒。二叉树是递归定义的,因此,与二叉树有关的题目基本都可以用递归思想解决。

第一道题目:

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的距离

样例

给出一棵如下的二叉树:

  1
 / \ 
2   3
   / \
  4   5

这个二叉树的最大深度为3.

这道题用递归的思路来解决的话,但是为了保证我们得到的是最大深度,应该最初的root左右子节点分开递归最后得到最大的, 代码还是非常简单的。

本质还是深度优先搜索;

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param root: The root of binary tree.
15      * @return: An integer.
16      */
17     public int maxDepth(TreeNode root) {
18         // write your code here
19         int leftDepth;
20         int rightDepth;
21         if(root == null ){
22             return 0;
23         }
24         else{
25             leftDepth = maxDepth(root.left)+1;
26             rightDepth = maxDepth(root.right)+1;
27             return Math.max(leftDepth,rightDepth);
28         }
29         
30     }
31 }
View Code

第二道题目:

给定一个二叉树,找出其最小深度。

二叉树的最小深度为根节点到最近叶子节点的距离。
样例

给出一棵如下的二叉树:

        1

     /     \ 

   2       3

          /    \

        4      5  

这个二叉树的最小深度为 2.

最开始看这道题的时候,其实很容易就想到这不是很简单吗?把最大深度的返回值改为两个里面最小的就可以。但其实并不是这样的。因为如果二叉树中出现了单个子节点为空的情况,返回值就会为0,但这个子节点并不是叶节点。

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param root: The root of binary tree.
15      * @return: An integer.
16      */
17     public int minDepth(TreeNode root) {
18         // write your code here
19         if(root == null )    return 0;
20         int leftDepth = minDepth(root.left);
21         int rightDepth = minDepth(root.right);
22         if(leftDepth==0||rightDepth ==0){//主要是对左右子节点是否有单个为空的情况进行判断
23             return 1+rightDepth + leftDepth;
24         }  else {
25             return 1+Math.min(rightDepth,leftDepth);
26         }
27     }
28 }
posted @ 2015-11-13 00:47  码代码的banana  阅读(181)  评论(0编辑  收藏  举报