236. The nearest common ancestor of the binary tree (java implementation) --LeetCode

topic:

Given a binary tree, find the nearest common ancestor of two specified nodes in the tree.

The definition of the nearest common ancestor in Baidu Encyclopedia is: "For two nodes p and q of the rooted tree T, the nearest common ancestor is expressed as a node x, so that x is the ancestor of p and q and the depth of x is as large as possible (A node can also be its own ancestor)."

For example, given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]

Insert picture description here

Example 1:

输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。

Example 2:

输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出: 5
解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。

Description:

  • The values ​​of all nodes are unique.
  • p and q are different nodes and both exist in the given binary tree.

Solution 1: Recursion

/**
 * 思路:
 * 公共祖先可能的3种情况:
 * 左子树上p/q
 * 右子树上p/q
 * 根节点
 *
 * 因为是递归,使用函数后可认为左右子树已经算出结果
 * 如果root为null返回null,左右子树一旦找到一个pq就返回节点
 * 不断的递归左右子树
 * 如果左子树为null,则公共节点在右子树上,若右子树为null反之。
 * 如果左右子树都不为null(左子树找到p,或者是q。或者是右子树)返回根节点
 */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    
    
        if (root==null||root==p||root==q)return root;
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        return left==null?right:right==null?left:root;
    }

Time complexity: On

Space complexity: O1
Insert picture description here

Solution 2: Iteration

    /**
     * 思路:
     * map中存当前节点,最近的祖先
     * set中存祖先
     *
     * 遍历所有节点,在map中存放子父关系
     * 获取map中p节点所有的父亲节点,存放在set中
     * 查看set,如果没有q(说明q有两种情况。第一种:q节点在p的下面。第二种:p,q不在根节点的同一侧)
     * 获取q的所有父亲节点,直到找到p。如果最后到了根还没找到。那说明p,q不在根节点的同一侧
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    
    
        HashMap<TreeNode, TreeNode> map = new HashMap<>();
        recursive(root,map);
        HashSet<TreeNode> set = new HashSet<>();
        while (p!=null){
    
    
            set.add(p);
            //root的父亲节点在map中不存在,返回null
            p = map.get(p);
        }
        while (!set.contains(q)){
    
    
            //不断的更新q,如果在set中存在了q说明就是p(q节点在p的下面,在set中找到q,此时的q就是p)。
            //如果在set中最后到了根,那说明p,q不在根节点的同一侧。仍然返回q就是此时的root
            q=map.get(q);
        }
        return q;
    }

    private void recursive(TreeNode root, HashMap<TreeNode, TreeNode> map) {
    
    
        if (root==null)return;
        if (root.left!=null)map.put(root.left,root);
        if (root.right!=null)map.put(root.right,root);
        recursive(root.left, map);
        recursive(root.right, map);
    }

Time complexity: On

Space complexity: On
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_38783664/article/details/113108345