每日一结

尤其注意递归的条件,分析好了各种情况。再下手写(不然堆积屎山堆积)。

例如求二叉树的最小深度,就分三种情况。

无子节点;有一个子节点;有两个子节点。那么就很明晰

public int minDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        else if(root.left == null) {
            return minDepth(root.right) + 1;
        }
        else if(root.right == null) {
            return minDepth(root.left) + 1;
        }else {
            return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
        }
    }
注意,递归函数的妙处,就在于能够在定义它的时候用它。编程思想尚待打开,不够开放自由大胆。

posted on 2022-09-21 17:13  xtdnn  阅读(21)  评论(0)    收藏  举报

导航