給定一個二叉樹, 找到該樹中兩個指定節點的最近公共祖先。
百度百科中最近公共祖先的定義為:“對于有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度盡可能大(一個節點也可以是它自己的祖先)。”
例如,給定如下二叉樹: root = [3,5,1,6,2,0,8,null,null,7,4]

示例 1:
輸入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
輸出: 3
解釋: 節點 5 和節點 1 的最近公共祖先是節點 3。
示例 2:
輸入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
輸出: 5
解釋: 節點 5 和節點 4 的最近公共祖先是節點 5。因為根據定義最近公共祖先節點可以為節點本身。
說明:
所有節點的值都是唯一的。
p、q 為不同節點且均存在于給定的二叉樹中。
非遞回解法:
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q){
struct TreeNode *stack[20000];
int top = 0, ancestorDepth = -1;
struct TreeNode *cur = root, *ancestor = NULL;
while ((cur || top>0) && ancestor != root){
while (cur){
stack[top++] = cur;
cur = cur->left;
}
cur = stack[--top];
if (top < ancestorDepth){
ancestor = cur;
ancestorDepth = top;
}
if (cur == p || cur == q){
if (ancestor) break;
ancestor = cur;
ancestorDepth = top;
}
cur = cur->right;
}
return ancestor;
}
完全沒看懂代碼的思路,請大佬詳細分析,我是幼兒園小朋友
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/230082.html
標籤:C語言
下一篇:CPU實作原子操作的原理
