zoukankan      html  css  js  c++  java
  • 236. Lowest Common Ancestor of a Binary Tree java solutions

    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 }
  • 相关阅读:
    os.fork()
    解决方案:WindowsError: [Error 2]
    Python遍历文件夹和读写文件的方法
    导航帖
    IDEA后缀补全及快捷键
    Codeforces-Round#614 Div2
    图论算法-欧拉回路 专题训练
    快速求出n!质因数的个数
    Codeforces-Round#589 Div2
    洛谷P3386二分图匹配
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5669209.html
Copyright © 2011-2022 走看看