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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
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 nodes5
and1
is3.
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 nodes5
and4
is5
, since a node can be a descendant of itself according to the LCA definition.
Note:
- All of the nodes' values will be unique.
- p and q are different and both values will exist in the binary tree.
這道求二叉樹的最小共同父節點的題是之前那道 Lowest Common Ancestor of a Binary Search Tree 的 Follow Up。跟之前那題不同的地方是,這道題是普通是二叉樹,不是二叉搜索樹,所以就不能利用其特有的性質,我們只能在二叉樹中來搜索p和q,然后從路徑中找到最后一個相同的節點即為父節點,可以用遞歸來實現,在遞歸函數中,首先看當前結點是否為空,若為空則直接返回空,若為p或q中的任意一個,也直接返回當前結點。否則的話就對其左右子結點分別調用遞歸函數,由於這道題限制了p和q一定都在二叉樹中存在,那么如果當前結點不等於p或q,p和q要么分別位於左右子樹中,要么同時位於左子樹,或者同時位於右子樹,那么我們分別來討論:
- 若p和q分別位於左右子樹中,那么對左右子結點調用遞歸函數,會分別返回p和q結點的位置,而當前結點正好就是p和q的最小共同父結點,直接返回當前結點即可,這就是題目中的例子1的情況。
- 若p和q同時位於左子樹,這里有兩種情況,一種情況是 left 會返回p和q中較高的那個位置,而 right 會返回空,所以最終返回非空的 left 即可,這就是題目中的例子2的情況。還有一種情況是會返回p和q的最小父結點,就是說當前結點的左子樹中的某個結點才是p和q的最小父結點,會被返回。
- 若p和q同時位於右子樹,同樣這里有兩種情況,一種情況是 right 會返回p和q中較高的那個位置,而 left 會返回空,所以最終返回非空的 right 即可,還有一種情況是會返回p和q的最小父結點,就是說當前結點的右子樹中的某個結點才是p和q的最小父結點,會被返回,寫法很簡潔,代碼如下:
解法一:
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (!root || p == root || q == root) return root; TreeNode *left = lowestCommonAncestor(root->left, p, q); TreeNode *right = lowestCommonAncestor(root->right, p , q); if (left && right) return root; return left ? left : right; } };
上述代碼可以進行優化一下,如果當前結點不為空,且既不是p也不是q,那么根據上面的分析,p和q的位置就有三種情況,p和q要么分別位於左右子樹中,要么同時位於左子樹,或者同時位於右子樹。我們需要優化的情況就是當p和q同時為於左子樹或右子樹中,而且返回的結點並不是p或q,那么就是p和q的最小父結點了,已經求出來了,就不用再對右結點調用遞歸函數了,這是為啥呢?因為根本不會存在 left 既不是p也不是q,同時還有p或者q在 right 中。首先遞歸的第一句就限定了只要遇到了p或者q,就直接返回,之后又限定了只有當 left 和 right 同時存在的時候,才會返回當前結點,當前結點若不是p或q,則一定是最小父節點,否則 left 一定是p或者q。這里的邏輯比較繞,不太好想,多想想應該可以理清頭緒吧,參見代碼如下:
解法二:
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (!root || p == root || q == root) return root; TreeNode *left = lowestCommonAncestor(root->left, p, q); if (left && left != p && left != q) return left; TreeNode *right = lowestCommonAncestor(root->right, p , q);
if (left && right) return root; return left ? left : right; } };
討論:此題還有一種情況,題目中沒有明確說明p和q是否是樹中的節點,如果不是,應該返回 nullptr,而上面的方法就不正確了,對於這種情況請參見 Cracking the Coding Interview 5th Edition 的第 233-234 頁。
Github 同步地址:
https://github.com/grandyang/leetcode/issues/236
類似題目:
Lowest Common Ancestor of a Binary Search Tree
參考資料:
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/