一道算法题目, 二行代码, Binary Tree

本文深入剖析了一个简洁高效的算法解决方案,通过仅使用两行代码来解决二叉树中只有一个孩子的节点计数问题。文章详细解释了代码背后的逻辑思维过程,包括对不同情况的判断和简化表达方式。此外,提供了详细的代码实现和GitHub链接,旨在展示编程中简化逻辑和提高效率的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

June 8, 2015

我最喜欢的一道算法题目, 二行代码. 

编程序需要很强的逻辑思维, 多问几个为什么, 可不可以简化.想一想, 二行代码, 五分钟就可以搞定; 2015年网上大家热议的 Homebrew 的作者 Max Howell 面试

Google 挂掉的一题, 二叉树反转, 七行代码, 相比二行代码, 情有可原!

Problem: return the count of binary tree with only one child

想一想, 你要写几行, 六七行, 或小于十行?

Solution:  two lines code:

 /**

* Great arguments:

1. Since first line is the discussion of “node==null”, there is no need to check node!=null before the function countOneChildNode call.

2. How to express only one child?

case 1: left child is not null; in other words, there is a left child: node.left!=null

case 2: right child is not null; node.right!=null)

case 3: node has two child

(node.left!=null) && (node.right!=null)

case 4: node has only one child (A: left child only, B: right child only, one true, one false; left child existed != right child existed; cannot be both false or both true)

(node.left!=null)!=(node.right!=null)

case 5: at least one child (one child or two child)

(node.left!=null) || (node.right!=null)

这道题非常好, 通过这道题, 你可以如何简化代码; 如果有一个出色的程序员, 有很强的逻辑思维能力, 想到只有一个孩子, 可以表示为一句话:  (node.left!=null)!=(node.right!=null)

*/

public static int countOneChildNode(Node node)

{

if(node==null) return 0;

return (((node.left!=null)!=(node.right!=null)?1:0)+countOneChildNode(node.left)+countOneChildNode(node.right));

}

Github for source code:

转载于:https://www.cnblogs.com/juliachenOnSoftware/p/4697235.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值