二叉树的最小深度(递归实现,java)

/**
 * 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;
        int leftminlength=run(root.left);
        int rightminlength=run(root.right);
        if(leftminlength==0&&rightminlength>0) return rightminlength+1;
        else if(rightminlength==0&&leftminlength>0) return leftminlength+1;
        else return (leftminlength<rightminlength)?leftminlength+1:rightminlength+1;
    }
}

采用递归的思想。要注意的是,如果左子树为空的话,返回的是右子树的最小深度+1

如果右子树为空的话,返回的是左子树的最小深度为1

如果左右子树都存在的话,返回的是左右子树的最小深度最小值+1


猜你喜欢

转载自blog.csdn.net/weixin_36564655/article/details/79825472
今日推荐