码迷,mamicode.com
首页 > 编程语言 > 详细

236. Lowest Common Ancestor of a Binary Tree java solutions

时间:2016-07-14 10:13:39      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

236. Lowest Common Ancestor of a Binary Tree java solutions

标签:

原文地址:http://www.cnblogs.com/guoguolan/p/5669209.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!