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 }
  • 相关阅读:
    读写excel文件
    数据库操作
    django项目搭建
    django基础
    string
    random函数
    vue-typescript入门
    Visual Studio 2019配置vue项目
    js css+html实现简单的日历
    python接口自动化4-绕过验证码登录(cookie)
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5669209.html
Copyright © 2011-2022 走看看