Leetcode 236. Lowest Common Ancestor of a Binary Tree
236. Lowest Common Ancestor of a Binary Tree
Total Accepted: 47687 Total Submissions: 165435 Difficulty: Medium
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4
For example, the lowest common ancestor (LCA) of nodes 5
and 1
is 3
. Another example is LCA of nodes 5
and 4
is 5
, since a node can be a descendant of itself according to the LCA definition.
思路:递归,定义lowestCommonAncestor函数返回值情况。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 13 //指针就是一个存放内存地址的变量,所以只要2个指针存放的内存地址相同,则可以说这2个指针相同 14 if(!root||root==p||root==q) return root; 15 TreeNode* left=lowestCommonAncestor(root->left,p,q); 16 TreeNode* right=lowestCommonAncestor(root->right,p,q); 17 /*if(!left&&!right){ 18 return NULL; 19 } 20 if(!left) return right; 21 if(!right) return left; 22 return root;*/ 23 return !left?right:(!right?left:root); 24 } 25 };