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

    /**
     * 236. Lowest Common Ancestor of a Binary Tree
     * 1. Time:O(n)  Space:O(h)
     * 2. Time:O(n)  Space:O(n)
     */
    
    // 1. Time:O(n)  Space:O(h)
    class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            if(root==null || root==p || root==q) return root;
            TreeNode left = lowestCommonAncestor(root.left,p,q);
            TreeNode right = lowestCommonAncestor(root.right,p,q);
            if(left!=null && right!=null) return root;
            else return left==null? right:left;
        }
    }
    
    // 2. Time:O(n)  Space:O(n)
    class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            Stack<TreeNode> stack = new Stack<>();
            HashMap<TreeNode,TreeNode> map = new HashMap<>();
            stack.push(root);
            map.put(root,null);
            while(!map.containsKey(p) || !map.containsKey(q)){
                TreeNode cur = stack.pop();
                if(cur.left!=null){
                    stack.push(cur.left);
                    map.put(cur.left,cur);
                }
                if(cur.right!=null){
                    stack.push(cur.right);
                    map.put(cur.right,cur);
                }
            }
            HashSet<TreeNode> set = new HashSet<>();
            while(p!=null){
                set.add(p);
                p = map.get(p);
            }
            while(q!=null){
                if(set.contains(q))
                    break;
                q = map.get(q);
            }
            return q;
        }
    }
    
  • 相关阅读:
    学期总结
    C语言II博客作业04
    C语言I博客作业08
    第十六周助教总结
    C语言||博客作业02
    期末助教总结
    S1 冒泡排序
    关于asp.net HttpUtility.UrlDecode解码问题
    asp.net Sql缓存依赖(SqlCacheDependency)
    解决aps.net 2.0中ajax调用webservice的问题
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12855343.html
Copyright © 2011-2022 走看看