每日一结
尤其注意递归的条件,分析好了各种情况。再下手写(不然堆积屎山堆积)。
例如求二叉树的最小深度,就分三种情况。
无子节点;有一个子节点;有两个子节点。那么就很明晰
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;
}
}
注意,递归函数的妙处,就在于能够在定义它的时候用它。编程思想尚待打开,不够开放自由大胆。
浙公网安备 33010602011771号