LeetCode 236. Lowest Common Ancestor of a Binary Tree

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来寻找所求节点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值