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; }
标签:Lowest,Binary,set,TreeNode,Tree,return,null,root,left 来源: https://www.cnblogs.com/feiflytech/p/15870041.html