Problem
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).”
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree
Method One
寻找两个节点的最深共同祖先。用dfs遍历二叉树。
class Solution {
TreeNode* ans;
public:
bool dfs(TreeNode* root, TreeNode* p, TreeNode* q) {
// 空节点时返回false
if (root == nullptr) return false;
// dfs遍历
bool left = dfs(root->left, p, q);
bool right = dfs(root->right, p, q);
// 判断当前节点是否为所求节点
// (left&&right) 第一种情况:当左子树和右子树分别包含p、q中的某个节点时,该节点为所求节点。
// (left||right&&(root==p||root==q)) 第二种情况:左子树或者右子树包含p、q中的某个节点,并且当前节点为p、q中的另一个节点时,该节点为所求节点。
if ((left&&right)||(left||right)&&(root==p||root==q)) ans = root;
// 左子树或右子树包含p、q中的某个节点||当前节点为p或q
return left||right||(root==p||root==q);
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
dfs(root, p, q);
return ans;
}
};
还见到了一种更直观的dfs
bool dfs(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root==nullptr) return false;
// 在当前节点
bool now = root==p||root==q;
// 在左节点
bool left = dfs(root->left, p, q);
// 在右节点
bool right = dfs(root->right, p, q);
if ((left&&right)||((left||right)&&now)) ans = root;
return left||right||now;
}
Method Two
一开始想到的是遍历两遍二叉树,记录父节点,之后匹配。
发现可以继续改进:用数组存储二叉树的节点值(非null节点的null子节点不能忽略以保证构成完全二叉树),之后利用二叉树的性质:父节点的位置为当前位置/2
来寻找所求节点。