ACM小技巧 - 多对象其一判空简写

背景

一般在二叉树比较常见这种情景,比如我想判断仅仅“左节点或右节点其中一个为空”就 dosomething...,两个对象还好,那如果是多叉树呢?岂不是要排列组合啦~

常见代码

if ((null == root.left && null != root.right) || (null != root.left && null == root.right)) {
    // dosomething...
}

优化代码

if (root.left == null && root.right == null) return; 

if (root.left == null || root.right == null) {
    // dosomething...
}

猜你喜欢

转载自blog.csdn.net/Dream_Weave/article/details/124352579