Created
December 4, 2013 06:55
-
-
Save liuml07/7783420 to your computer and use it in GitHub Desktop.
Find the lowest common ancestor of two tree nodes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
TreeNode *LCA(TreeNode *root, TreeNode *p, TreeNode *q) { | |
if (root == nulltpr || root == p || root == q) | |
return root; | |
else { | |
TreeNode *L = LCA(root->left, p, q); | |
TreeNode *R = LCA(root->right, p, q); | |
if (L && R) | |
return root; | |
else | |
return L ? L : R; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment