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.
 
 
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int run(TreeNode root) {
        if(root==null){
            return 0;
        }else{
            if(root.left==null){
                return 1+run(root.right);
            }else if(root.right==null){
                return 1+run(root.left);
            }else{
                return Math.min(1+run(root.right),1+run(root.left));
            }
        }
    }
}

这道题其实就是一道简单的递归,可是在写的时候还是遇到一点小问题,感觉还是对递归不够熟悉,还无法直接捋出这个递归的结构。

总结一下   用递归实现一个问题的思考思路:

1.先用语言描述出来,就是描述出想用这个递归来实现什么,考虑一层递归需要实现什么功能,嵌套起来才能实现整个问题。

2.关键是想的过程, 递归函数的基本功能模板   在子问题已经解决的情况下,使用子问题的返回值来结合自己当前情况,返回一个值给自己的父级

3.还有一个就是递归的返回情况,最边界情况下的处理情况

posted @ 2016-09-15 12:40  萝卜er  阅读(147)  评论(0)    收藏  举报