/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution{Map<Integer,TreeNode>parent=newHashMap<Integer,TreeNode>();//记录P所有父节点的值Set<Integer>visited=newHashSet<Integer>();//遍历,记录每个节点的父节点//key 左右节点的值 value 父节点publicvoiddfs(TreeNoderoot){if(root.left!=null){parent.put(root.left.val,root);dfs(root.left);}if(root.right!=null){parent.put(root.right.val,root);dfs(root.right);}}publicTreeNodelowestCommonAncestor(TreeNoderoot,TreeNodep,TreeNodeq){dfs(root);//p向上移动,并保存p的所有父节点的值//重要条件:所有的val不相等,所以存储父节点的值就可以了while(p!=null){visited.add(p.val);p=parent.get(p.val);}//q向上移动,如果p的父节点值包含q的父节点值while(q!=null){if(visited.contains(q.val)){returnq;}q=parent.get(q.val);}returnnull;}}