/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ classSolution{
public Map<TreeNode,TreeNode> map = new HashMap<>(); public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){ dfs(root); TreeNode pNode = p, qNode = q; Set<TreeNode> set = new HashSet<>(); while(pNode != null) { set.add(pNode); pNode = map.get(pNode); } while(qNode != null) { if (set.contains(qNode)) { return qNode; } qNode = map.get(qNode); } returnnull; }
publicvoiddfs(TreeNode node){ if (node == null) return; if (node.left != null) { map.put(node.left, node); dfs(node.left); } if (node.right != null) { map.put(node.right, node); dfs(node.right); } } }