[LeetCode]236 二叉树的最近公共父亲节点

Lowest Common Ancestor of a Binary Tree(二叉树的最近公共父亲节点)

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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
这里写图片描述
For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

给定一个二叉树和所要查找的两个节点,找到两个节点的最近公共父亲节点(LCA)。比如,节点5和1的LCA是3,节点5和4的LCA是5。


解题思路

本题与LeetCode 235的区别就是由二叉查找树变为了二叉树,即数据从有序变为了无序,那么就不能通过root的值和两个节点的值的大小关系来划分查找区域。在题235的代码基础做了些许变动,同样使用递归搜索的方法,当root非空时,对root->left和root->right分别进行搜索。若搜索结果均非空,说明两个节点分别位于左右子树之中,LCA则为root;若只有一个结果为空,则LCA是另一个非空的节点;若结果均空,则返回NULL。


c++代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (!root || root == p || root == q)
            return root;
        TreeNode* left = lowestCommonAncestor(root->left,p,q);
        TreeNode* right = lowestCommonAncestor(root->right,p,q);
        if (left && right)
            return root;
        if (!left)
            return right;
        if (!right)
            return left;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值