zoukankan      html  css  js  c++  java
  • leetcode——236. 二叉树的最近公共祖先

    并没有理解这种递归想法:

    class Solution:
        def __init__(self):
            self.ans=None
        def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
            def recurse_tree(current_node):
                if not current_node:
                    return False
                left=recurse_tree(current_node.left)
                right=recurse_tree(current_node.right)
                mid=current_node==p or current_node==q
                if mid + left + right >= 2:
                    self.ans = current_node
                return mid or left or right
            recurse_tree(root)
            return self.ans
    执行用时 :120 ms, 在所有 python3 提交中击败了28.70%的用户
    内存消耗 :28.7 MB, 在所有 python3 提交中击败了5.11%的用户
     
    相比较而言,还是使用父指针迭代的思想更好理解:
    class Solution:
        def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
            stack=[root]
            parent={root:None}
            while p not in parent or q not in parent:
                node=stack.pop()
                if node.left:
                    parent[node.left]=node
                    stack.append(node.left)
                if node.right:
                    parent[node.right]=node
                    stack.append(node.right)
            ancestors=set()
            while p:
                ancestors.add(p)
                p=parent[p]
            while q not in ancestors:
                q=parent[q]
            return q
    执行用时 :80 ms, 在所有 python3 提交中击败了97.18%的用户
    内存消耗 :17.8 MB, 在所有 python3 提交中击败了97.91%的用户
     
    ——2019.11.19
    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    js相关小实例——滚动监听
    js相关小实例——进度条
    数据库的连接
    php函数
    php语法
    php基础上
    列表 选择背景变化
    飞入
    移动列表内容
    javascript的语法
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11890856.html
Copyright © 2011-2022 走看看