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
    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    HDU 3746 Cyclic Nacklace 环形项链(KMP,循环节)
    13 python 常用的内置方法介绍
    12、反射方法
    11 绑定方法与非绑定方法
    10 python 封装----@property的用法
    9 python 多态与多态类
    8 python 抽象类
    7 python 类的组合
    4.1、内建函数
    6 python 继承与派生
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11890856.html
Copyright © 2011-2022 走看看