加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[LeetCode] Lowest Common Ancestor of a Binary Tree

发布时间:2020-12-14 04:49:16 所属栏目:大数据 来源:网络整理
导读: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 b

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

Given the following binary search tree:? root =?[3,5,1,6,2,8,null,7,4]

        _______3______
       /                  ___5__          ___1__
   /              /         6      _2       0       8
         /           7   4

Example 1:

Input: root,p = 5,q = 1
Output: 3
Explanation: The LCA of of nodes  and  is 
513.

Example 2:

Input: root,q = 4
Output: 5
Explanation: The LCA of nodes  and  is,since a node can be a descendant of itself
             according to the LCA definition.545

求二叉搜索树的最低公共祖先结点

根据二叉搜索树的性质:位于左子树的结点都比父结点小,位于右子树的结点都比父结点大。

两个结点的最低公共祖先:指两个结点都出现在某个结点的子树中,我们可以从根结点出发遍历一棵树,每遍历一个结点判断两个输入是否在其子树中,如果在其子树中,分别遍历它的所有结点并判断两个输入结点是否在其子树中。直到找到第一个结点,它的子树中同时包括两个输入结点但它的子结点却没有。那么该结点就是最低的公共祖先。

递归

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root,TreeNode* p,TreeNode* q) {
        if (root == nullptr || p == nullptr || q == nullptr)
            return root;
        if (max(p->val,q->val) < root->val)
            return lowestCommonAncestor(root->left,p,q);
        else if (min(p->val,q->val) > root->val)
            return lowestCommonAncestor(root->right,q);
        else
            return root;
    }
};

迭代

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root,TreeNode* q) {
        if (!root || !p || !q)
            return nullptr;
        int left = p->val,right = q->val;
        while (root)
        {
            int target = root->val;
            if (target > left && target > right)
                root = root->left;
            else if (target < left && target < right)
                root = root->right;
            else
                break;
        }
        return root;
    }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读