參考資訊:
https://www.cnblogs.com/grandyang/p/4641968.html
題目:
解答:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ struct TreeNode* lowestCommonAncestor(struct TreeNode *root, struct TreeNode *p, struct TreeNode *q) { struct TreeNode *l = NULL; struct TreeNode *r = NULL; if (!root || (root == p) || (root == q)) { return root; } l = lowestCommonAncestor(root->left, p, q); r = lowestCommonAncestor(root->right, p, q); if (l && r) { return root; } return l ? l : r; }