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).”

    _______3______
   /              \
___5__          ___1__

/ \ / \
6 _2 0 8
/ \
7 4
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.

思路分析

一个典型的二叉树递归查找的题目。我的思路是困在不知道如何递归向上,事实上先序遍历已经自动处理这个情况了,根据题意,我们知道,只有两种情况需要考虑,一种就是p或q是另外一个结点的子节点,一种就是两者属于同一棵树的子节点,现在就是要找出这颗树的根节点。很明显我们要用先序遍历来解决这个问题(可以利用自底向上的递归结果),如果是第一种情况,很明显,我们先遍历到的节点一定是另一节点的父节点;如果是第二种情况,那么必然在某一轮的递归中找到该父节点(向上过程),最终先序遍历的完整返回结果就是我们要找的ancestor。

代码实现

/**
 * 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 == nullptr||root == p || root == q) return root;
        auto left = lowestCommonAncestor(root->left,p,q);
        auto right = lowestCommonAncestor(root->right,p,q);
        if(left&&right) return root;
        return left==nullptr?right:left;
    }

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值