Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______3______ / ___5__ ___1__ / \ / 6 _2 0 8 / 7 4
For example, the lowest common ancestor (LCA) of nodes 5
and 1
is 3
. Another example is LCA of nodes 5
and 4
is 5
, since a node can be a descendant of itself according to the LCA definition.
建立节点的parent 字典,p 、q 分别往前遍历即可。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 12 Map<TreeNode,TreeNode> parent = new HashMap<TreeNode,TreeNode>(); 13 Deque<TreeNode> s = new ArrayDeque<TreeNode>(); 14 parent.put(root,null); 15 s.add(root); 16 while(!parent.containsKey(p) || !parent.containsKey(q)){ 17 TreeNode n = s.pop(); 18 if(n.left != null){ 19 parent.put(n.left,n); 20 s.add(n.left); 21 } 22 if(n.right != null){ 23 parent.put(n.right,n); 24 s.add(n.right); 25 } 26 } 27 Set<TreeNode> set = new HashSet<TreeNode>(); 28 while(p!= null){ 29 set.add(p); 30 p = parent.get(p); 31 } 32 while(!set.contains(q)) q = parent.get(q); 33 return q; 34 } 35 }
时间: 2024-11-06 15:18:08