236. Lowest Common Ancestor of a Binary Tree Java solutions

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.