Given a binary tree, find the lowest common ancestor (LCA) of the Given nodes in the tree.
According to the definition of the LCA in Wikipedia: "The lowest common ancestor is defined between," nodes V and W as the L Owest node in T, have 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 and are 5
1
3
. Another example is LCA of nodes 5
4
5
and are, since a node can be a descendant of itself according to the L CA definition.
The parent dictionary of the node is established, and the P and Q are traversed forward respectively.
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 */Ten Public classSolution { One PublicTreeNode lowestcommonancestor (TreeNode root, TreeNode p, TreeNode q) { Amap<treenode,treenode> parent =NewHashmap<treenode,treenode>(); -deque<treenode> s =NewArraydeque<treenode>(); -Parent.put (Root,NULL); the S.add (root); - while(!parent.containskey (P) | |!Parent.containskey (q)) { -TreeNode n =S.pop (); - if(N.left! =NULL){ + Parent.put (n.left,n); - S.add (n.left); + } A if(N.right! =NULL){ at Parent.put (n.right,n); - S.add (n.right); - } - } -Set<treenode> set =NewHashset<treenode>(); - while(p!=NULL){ in Set.add (p); -p =Parent.get (p); to } + while(!set.contains (q)) Q =Parent.get (q); - returnQ; the } *}
236. Lowest Common Ancestor of a Binary Tree Java solutions