236. Lowest Common Ancestor of a Binary Tree
_______3______
/ \
___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
// assume the node exists in the tree
if(!root || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
// there must be three cases {left, right, root} contains CLA
return !left? right: !right ? left: root;
}
};Previous297. Serialize and Deserialize Binary TreeNext235. Lowest Common Ancestor of a Binary Search Tree
Last updated
Was this helpful?