算法题---求二叉树的最近公共祖先

 

 

 

思路一:非递归方法

1. 找到两个节点的路径的逆序链表,将题转换成两个链表第一个公共节点的问题。

1.2 两个链表求第一个公共节点

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode *node1 = headA;
        ListNode *node2 = headB;
        
        while (node1 != node2) {
            node1 = node1 != NULL ? node1->next : headB;
            node2 = node2 != NULL ? node2->next : headA;
        }
        return node1;
    }
};

 

2. 找到两个节点的路径,将其存储到两个数组中,遍历两个数组,返回两个数组第一次不相等的上一个节点。

思路二:递归方法

def solution(root, p, q):
    if root == None or p == root or q == root:
        return root
    left = solution(root.left, p, q)
    right = solution(root.right, p, q)
    if left and right:
        return root
    if not left and not right:
        return None
    if not left and right:
        return right
    if not right and left:
        return left

 

 

参考

https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/solution/pythonti-jie-bu-tong-si-kao-fang-shi-ying-he-mian-/

posted @ 2020-10-21 22:42  威威后花园  阅读(180)  评论(0编辑  收藏  举报