Leetcode 236 Solution

This article provides solution to leetcode question 236 (lowest-common-ancestor-of-a-binary-tree)

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree

Solution

/** * 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 { TreeNode* m_res; public: int findLowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root == 0) return 0;
int root_cnt = 0;
if (root == p || root == q) root_cnt = 1;
int left_cnt = findLowestCommonAncestor(root->left, p, q); int right_cnt = findLowestCommonAncestor(root->right, p, q);
if ((left_cnt == 1 && right_cnt == 1) || (root_cnt == 1 && left_cnt + right_cnt == 1)) m_res = root;
return root_cnt + left_cnt + right_cnt; }
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { findLowestCommonAncestor(root, p, q);
return m_res; } };