An algorithm topic, two lines of code, Binary Tree

Source: Internet
Author: User

June 8, 2015

One of my favorite algorithm topics, two lines of code.

Programming requires a strong logical thinking, ask a few why, can simplify. Think about it, two lines of code, five minutes can be done; 2015 online everyone hot Homebrew author Max Howell interview

Google hangs off a problem, binary tree inversion, seven lines of code, compared to two lines of code, excusable!

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

Think about it, do you want to write a few lines, six or seven lines, or less than 10 lines?

Solution:two Lines Code:



* Great arguments:

1. Since first line is the discussion of "node==null", there are no need to check node!=null before the function Countonech Ildnode call.

2. How to express only one child?

Case 1:left child is not null; In other words, there are a left child:node.left!=null

Case 2:right child is not null; Node.right!=null)

Case 3:node has both child

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

Case 4:node have only one child (A:left-only, b:right-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 both child)

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

This problem is very good, through this problem, you can simplify the code; If there is a good programmer, have a strong logical thinking ability, think of only one child, can be expressed as a sentence: (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:


An algorithm topic, two lines of code, Binary Tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.