1. 程式人生 > 實用技巧 >236. Lowest Common Ancestor of a Binary Tree

236. Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to thedefinition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes pand qas the lowest node in T that has both pand qas descendants (where we allowa node to be a descendant of itself).”

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Example 3:

Input: root = [1,2], p = 1, q = 2
Output: 1

Constraints:

  • The number of nodes in the tree is in the range[2, 105].
  • -109<= Node.val <= 109
  • AllNode.valareunique.
  • p != q
  • pandqwillexist in the tree.
/**
 * 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: //還是遞迴解法:在左子樹中遞迴找p或q,如果找到一個就返回;在右子樹中找p或q如果找到一個就返回那個節點,沒找到就返回NULL。 //如果左子樹中找到一個,右子樹中也找到一個,那麼這兩個子樹的根節點就是結果。 //如果左子樹中沒有找到,那麼返回空,說明兩個節點都在右子樹。否則都在左子樹。 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(root==NULL) return NULL; if(root==p||root==q) return root; TreeNode* ltree=lowestCommonAncestor(root->left,p,q); TreeNode* rtree=lowestCommonAncestor(root->right,p,q); //分別在左右子樹中找到 if(ltree&&rtree) return root; //右三種情況在此處返回 //在左右某個子樹中沒找到任一個p或q //第一次在當前節點左子樹或者右子樹中找到p或q //當前節點的左右子樹找到p'q return ltree?ltree:rtree; } };