1676. Lowest Common Ancestor of a Binary Tree IV

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;
    }

 

上一篇:yarn/npm/cnpm报错 Error: unable to verify the first certificate


下一篇:Oracle--sqlplus如何设置SQLPlus结果显示的宽度