1. 程式人生 > >leetcode 235|236. Lowest Common Ancestor of a Tree

leetcode 235|236. Lowest Common Ancestor of a Tree

235Lowest Common Ancestor of a Binary Search Tree

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

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

).”

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

由於是二叉樹,有個特點就是如果一個數比當前值大,另一個比當前值小,就肯定在左右兩邊。當前點肯定就是最小公共祖先。

/**
 * 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)
    {
        int minkey = min(p->val, q->val), maxkey = max(q->val, p->val);
        TreeNode * now = root;
        while (now)
        {
            if (now->val < minkey)
                now = now->right;
            else if (now->val > maxkey)
                now = now->left;
            else
                return now;
        }
        return nullptr;
    }
};


236Lowest 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.


這個題是一般的二叉樹。所以就先搜到root到要求點的兩條路徑。然後考察路徑在哪不一樣了。那就是最小公共祖先。

/**
 * 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)
    {
        //先DFS求到這兩個節點的路徑。
        vector<TreeNode*> routeP;
        helper(routeP, p, root);
        
        vector<TreeNode*> routeQ;
        helper(routeQ, q, root);
        
        //看這兩個路徑在哪不一樣。之前那個就是公共路徑。
        TreeNode* ret = nullptr;
        for (int i = 0; i < min(routeP.size(), routeQ.size()); i++)
        {
            if (routeP[i] == routeQ[i])
                ret = routeP[i];
            else
                break;
        }
        return ret;
    }
    
    bool helper(vector<TreeNode*> &route, TreeNode* target, TreeNode* now)
    {
        if (!now)
            return false;
        
        route.push_back(now);
        
        if (now == target)
        {
            return true;
        }
        
        if (helper(route, target, now->left) || helper(route, target, now->right))
            return true;
        
        route.pop_back();
        return false;
    }
};


相關推薦

Leetcode 235: Lowest Common Ancestor of a Binary Search Tree

pre target class defined als tor span lee define Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given no

LeetCode 236. Lowest Common Ancestor of a Binary Tree; 235. Lowest Common Ancestor of a Binary Search Tree

lowest node nan stc leet common lca ear 尋找 236. Lowest Common Ancestor of a Binary Tree 遞歸尋找p或q,如果找到,層層向上返回,知道 root 左邊和右邊都不為NULL:if (lef

leetcode 236-Lowest Common Ancestor of a Binary Tree(medium)

where med follow des init binary ret find col Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

LeetCode-236 lowest common ancestor of a binary tree 二叉樹的最近公共祖先

題目連結 https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/ 題意         中文題,就是給出一個一般的二叉樹,求其最近公共祖先,並且宣告節點

LeetCode-235 lowest-common-ancestor-of-a-binary-search-tree 二叉搜尋樹的最近公共祖先

題目連結 LeetCode-235 lowest-common-ancestor-of-a-binary-search-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

[LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree

Lowest Common Ancestor of a Binary Search Tree Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the

LeetCode 236. Lowest Common Ancestor of a Binary Tree

題解 求解最近公共父節點,比較經典的題目。 思路是二路dfs。沿著左右下行,終結條件是 空節點 或者 root==(p or q)。 那麼此時,Left Right 有三種情況 均非空:左右兩子樹剛好

JavaScript刷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 Wiki

LeetCode(46) Lowest Common Ancestor of a Binary (Search) Tree

Lowest Common Ancestor of a Binary Search Tree 題目描述 Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nod

leetcode 235|236. Lowest Common Ancestor of a Tree

235. Lowest Common Ancestor of a Binary Search Tree Given a binary search tree (BST), find the lowest common ancestor (LCA) of two giv

(C++)LeetCode#236. Lowest Common Ancestor of a Binary Tree

題目:給定一個棵二叉樹的兩個節點o1/o2,求兩個節點的最近公共祖先(LCA) 難度:Medium 思路: 方法1.記錄路徑:先遍歷二叉樹,分別得到從根節點到o1/o2的兩個路徑儲存在vector中

LeetCode-235.Lowest Common Ancestor of a Binary Search Tree

turn ads lca earch blog ancestor eno unique rdquo Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given no

LeetCode-236.Lowest Common Ancestor of a Binary Tree

pre diff wiki exist bsp tar load tor dia Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. Acco

leetcode——Lowest Common Ancestor of a Binary Tree

sdn 右值 split arc candidate tex 查找樹 也好 左右 題目 Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in t

Leetcode】235. Lowest Common Ancestor of a Binary Search Tree

tween target amp des esc blog cor 循環 ive Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in

leetcode 236. 二叉樹的最近公共祖先(Lowest Common Ancestor of a Binary Tree) beat 99.05%

給定一個二叉樹, 找到該樹中兩個指定節點的最近公共祖先。 百度百科中最近公共祖先的定義為:“對於有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度儘可能大(一個節點也可以是它自己的祖先)。” 例如,給定如下二叉樹:  root

LeetCode-Lowest Common Ancestor of a Binary Tree

一、Description 題目描述:給定一個二叉樹和兩個結點p和q,找出p和q的最近公共祖先。 二、Analyzation 通過遍歷分別找到從根節點到p和q的路徑,放入一個棧中。如果兩個棧的大小相同,則同時出棧直到兩個棧出棧的結點值相同,則為最近公共祖先,如果兩個棧的大小不同(

Leetcode】235. Lowest Common Ancestor of a Binary Search Tree二叉搜尋樹的最近公共祖先

Lowest Common Ancestor of a Binary Search Tree 二叉搜尋樹的最近公共祖先 Given a binary search tree (BST), find the lowest common ancestor (LCA) of two giv

LeetCode 236 -- 二叉樹的最近公共祖先 ( Lowest Common Ancestor of a Binary Tree ) ( C語言版 )

題目描述 :  解題思路 : 使用遞迴查詢 , 如果有一個節點與根節點匹配 , 那麼直接返回根節點 , 否則依次在左子樹和右子樹中查詢 ,並且用left 和right分別記錄左子樹的返回值和右子樹的返回值 , 如果節點都存在左子樹中 , 那麼right就一定為NULL