您的位置:首页 > 其它

[LeetCode]Minimum Depth of Binary Tree

2014-10-21 21:26 281 查看
题目:给定一颗二叉树,求出这颗二叉树的最小高度

算法:深度优先算法

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int minimumDepth = 0x3fffffff;
    
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        dfs(root, 1);
        return minimumDepth;
    }
    
    public void dfs(TreeNode node, int sum) {
        if (node.left==null && node.right==null) {
            if (sum < minimumDepth) {
                minimumDepth = sum;
            }
            return ;
        }
        
        if (node.left != null) {
            dfs(node.left, sum+1);
        }
        if (node.right != null) {
            dfs(node.right, sum+1);
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: