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:
Https://github.com/jianminchen/leetcode-tree/blob/master/TreeDemo.cs
An algorithm topic, two lines of code, Binary Tree