給定一個二叉樹, 找到該樹中兩個指定節點的最近公共祖先。
百度百科中最近公共祖先的定義為:“對于有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度盡可能大(一個節點也可以是它自己的祖先)?!?/p>
LeetCode:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
解題思路分析
首先對于二叉樹而言,某個節點本身也稱為該節點的祖先。其次兩個節點的公共祖先一共應該有三種情況:
① q是p的子節點,那么最近公共祖先為 p
② p是q的子節點,那么最近公共祖先為q
③ p和q分別為某個節點的左右節點,那么最近公共祖先為該節點
def lowestCommonAncestor(root, p, q):
def helper(root):
if not root or root == p or root == q: return root
? left = helper(root.left)
right = helper(root.right)
if not left and not right: return
if not left: return right
if not right : return left
return root
return helper(root)
升級思路
關于二叉樹的最近公共祖先,也能想到在iOS中如何找到兩個view的最近superView。
首先,拿到當前view的所有superView的集合
NSMutableArray *arr = [NSMutableArray array];
while (cls) {
[arr addObject:cls];
cls = [cls superview];
}
return arr;
其次,如果找到兩個集合中最近的superView,那么從該節點開始后面的數量一致,根據這個規律可知:
① viewA 在上層,viewB在下層,那么viewA.count >viewB.count
image
repeat_count = Min(viewA.count, viewB.count)
start_posA = viewA.count - repeat_count
start_posB = viewB.count - repeat_count
② 按照repeat_count從 MinCount - 0的順序進行查找
while (repeat_count > 0) {
PASS
}
③ 具體實現
- (UIView *)commonSuperViewBetween:(UIView *)cls1 and:(UIView *)cls2 {
NSArray *arr1 = [self getSuperViewArray:cls1];
NSArray *arr2 = [self getSuperViewArray:cls2];
NSUInteger count = MIN(arr1.count, arr2.count);
while (count > 0) {
UIView *view_inA = [arr1 objectAtIndex:arr1.count - count];
UIView *view_inB = [arr2 objectAtIndex:arr2.count - count];
if (view_inA == view_inB) {
return view_inA;
}
count --;
}
return nil;
}