码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode] 111. Minimum Depth of Binary Tree Java

时间:2017-07-19 23:38:07      阅读:317      评论:0      收藏:0      [点我收藏+]

标签:tree node   ini   turn   nod   oid   节点   mat   long   ==   

题目:

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 a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        if(root==null) return 0;
        int[] minHeight = {0};
        getHeight(minHeight,1,root);
        return minHeight[0];
    }

    public void getHeight(int[] minHeight,int height,TreeNode node){      //遍历树,得到每个点的高度
        if(node.left!=null){
            getHeight(minHeight,height+1,node.left);
        }
        if(node.right!=null){
            getHeight(minHeight,height+1,node.right);
        }
        if(node.left==null&&node.right==null){      //对根节点,做判断,看是否是当前最小
            if(minHeight[0]!=0){       //当前子节点高度和先前最小值相比
                minHeight[0]=Math.min(height,minHeight[0]);
            }else{      //第一次初始化
                minHeight[0]=height;
            }
        }
    }
}

 

[LeetCode] 111. Minimum Depth of Binary Tree Java

标签:tree node   ini   turn   nod   oid   节点   mat   long   ==   

原文地址:http://www.cnblogs.com/271934Liao/p/7208504.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!