In this problem, it is important to fully understand the definition of least common ancestor of 2 nodes:
it means: (from leetcode blog: 点击打开链接)
_______3______
/ \
___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4
If you are not so sure about the definition of lowest common ancestor (LCA), please refer to my previous post:Lowest Common Ancestor of a Binary Search Tree (BST) or the definition of LCA here. Using the tree above as an example, the LCA of nodes 5 and 1 is 3. Please note that LCA for nodes 5 and 4 is 5.
Here is the whole code with comments. Really good design by Hawstein.
// Ch4.6: Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree.
// Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.
//http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-tree-part-i.html
//the LCA of nodes 5 and 1 is 3. Please note that LCA for nodes 5 and 4 is 5.
#include
#include
#include
#include