zoukankan      html  css  js  c++  java
  • 二叉树中任意两个节点的最近公共祖先

    public class Solution {  
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {  
            //发现目标节点则通过返回值标记该子树发现了某个目标结点  
            if(root == null || root == p || root == q) return root;  
            //查看左子树中是否有目标结点,没有为null  
            TreeNode left = lowestCommonAncestor(root.left, p, q);  
            //查看右子树是否有目标节点,没有为null  
            TreeNode right = lowestCommonAncestor(root.right, p, q);  
            //都不为空,说明做右子树都有目标结点,则公共祖先就是本身  
            if(left!=null&&right!=null) return root;  
            //如果发现了目标节点,则继续向上标记为该目标节点  
            return left == null ? right : left;  
        }  
    }  

    思路:从根节点开始遍历,如果node1和node2中的任一个和root匹配,那么root就是最低公共祖先。 如果都不匹配,则分别递归左、右子树,如果有一个 节点出现在左子树,并且另一个节点出现在右子树,则root就是最低公共祖先.  如果两个节点都出现在左子树,则说明最低公共祖先在左子树中,否则在右子树。

    感觉很奇妙。引申的问题

    如果给定的不是二叉树,而是二叉搜索树呢?会比较简单一点,如果是带有指向父节点的指针的树,可以转化为两个链表求交汇点的问题。

     235. 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 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) {
            while((root -> val - p -> val)*(root -> val - q -> val) > 0 ){
                root = root -> val > p -> val ? root -> left : root -> right;
            }
            return root;
        }
    };
  • 相关阅读:
    [每日一题]一道面试题是如何引发深层次的灵魂拷问?
    值得关注的内推:字节内推「社招,校招及提前批,实习生」,每日面试题
    《人在囧途》系列
    Jmeter(三十三)
    hive with as 语法
    红蓝紫实战攻防演习手册2020
    hfish 集群蜜罐搭建
    CTF之MISC练习
    Struts2 S2-061(CVE-2020-17530)漏洞复现
    解决Windows资源管理器呼出上下文菜单(右键菜单)导致卡死的问题
  • 原文地址:https://www.cnblogs.com/simplepaul/p/7702655.html
Copyright © 2011-2022 走看看