首页 > 代码库 > Minimum Depth of Binary Tree

Minimum Depth of Binary Tree

题目:给定一颗二叉树,求出这颗二叉树的最小高度

算法:深度优先算法

/**
 * 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);
        }
    }
}

Minimum Depth of Binary Tree