1. 程式人生 > >[LeetCode] 236. Lowest Common Ancestor of a Binary Tree

[LeetCode] 236. Lowest Common Ancestor of a Binary Tree

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 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).”
Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
這裡寫圖片描述


Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of of nodes 5 and 1 is 3.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Note:
All of the nodes’ values will be unique.
p and q are different and both values will exist in the binary tree.

解法1:遞迴

我們可以用遞迴來實現,在遞迴函式中,我們首先看當前結點是否為空,若為空則直接返回空,若為p或q中的任意一個,也直接返回當前結點。否則的話就對齊左右子結點分別呼叫遞迴函式,由於這道題限制了p和q一定都在二叉樹中存在,那麼如果當前結點不等於p或q,那麼p和q要麼分別位於左右子樹中,要麼同時位於左子樹,或者同時位於右子樹,那麼我們分別來討論:
若p和q要麼分別位於左右子樹中,那麼對左右子結點呼叫遞迴函式,會分別返回p和q結點的位置,而當前結點正好就是p和q的最小共同父結點,直接返回當前結點即可,這就是題目中的例子1的情況。
若p和q同時位於左子樹,這裡有兩種情況,一種情況是left會返回p和q中較高的那個位置,而right會返回空,所以我們最終返回非空的left即可,這就是題目中的例子2的情況。還有一種情況是會返回p和q的最小父結點,就是說當前結點的左子樹中的某個結點才是p和q的最小父結點,會被返回。
若p和q同時位於右子樹,同樣這裡有兩種情況,一種情況是right會返回p和q中較高的那個位置,而left會返回空,所以我們最終返回非空的right即可,還有一種情況是會返回p和q的最小父結點,就是說當前結點的右子樹中的某個結點才是p和q的最小父結點,會被返回。

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root || p == root || q == root) return root;
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right= lowestCommonAncestor(root->right, p,q);
        if(left && right) return root;
        return left ? left : right;
    }
};

解法2:解法1的改進

如果當前結點不為空,且既不是p也不是q,那麼根據上面的分析,p和q的位置就有三種情況,p和q要麼分別位於左右子樹中,要麼同時位於左子樹,或者同時位於右子樹。我們需要優化的情況就是當p和q同時為於左子樹或右子樹中,而且返回的結點並不是p或q,那麼就是p和q的最小父結點了,已經求出來了,就不用再對右結點呼叫遞迴函數了,同樣,對返回的right也做同樣的優化處理。

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root || p == root || q == root) return root;
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        if(left && left != q && left != p) return left;
        TreeNode* right= lowestCommonAncestor(root->right, p,q);
        if(right && right != q && right != p) return right;
        if(left && right) return root;
        return left ? left : right;
    }
};

此題還有一種情況,題目中沒有明確說明p和q是否是樹中的節點,如果不是,應該返回NULL,而上面的方法就不正確了。

參考

http://www.cnblogs.com/grandyang/p/4641968.html