This problem is just as same as "235. Lowest Common Ancestor of a Binary Search Tree", the only difference is, 235 is two points, 1676 is 1~n points.

The solution is almost same, the only difference is in this solution, we use a set to check whether root meet one of the nodes:

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode[] nodes) {
        Set<Integer> set = new HashSet<>();
        for(TreeNode node:nodes){
            set.add(node.val);
        }
        return postOrder(root,  set);
    }
    private TreeNode postOrder(TreeNode root, Set<Integer> set){
        if(root==null)
            return null;
        if(set.contains(root.val))
            return root;
        TreeNode left = postOrder(root.left, set);
        TreeNode right = postOrder(root.right, set);
        if(left!=null && right!=null)
            return root;
        else if(left==null)
            return right;
        else
            return left;
    }

 

posted on 2022-02-08 08:55  阳光明媚的菲越  阅读(18)  评论(0编辑  收藏  举报