Leetcode 2096. Step-By-Step Directions From a Binary Tree Node to Another [Python]

一开始没看提示,没想LCA,先写了DFS的版本。结果第287个TC会TLE。建立一个parent的dic,用于往外dfs的时候找node的父节点。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
        self.parent = collections.defaultdict(TreeNode)
        self.dic = collections.defaultdict(TreeNode)
        que = collections.deque()
        que.append(root)
        que2 = collections.deque()
        while que:
            curnode = que.popleft()
            if curnode.val == startValue:
                que2.append(curnode)
            if curnode.val == destValue:
                que2.append(curnode)
            if len(que2) == 2:
                break
            if curnode.left:
                self.parent[curnode.left] = curnode
                que.append(curnode.left)
            if curnode.right:
                self.parent[curnode.right] = curnode
                que.append(curnode.right)
                       
        for node in que2:
            if node.val == startValue:
                startnode = node
                                                
        def dfs(node, res, destValue, meet, dic):
            if node.val in meet:return #题目说node val是唯一的
            meet.add(node.val)
            
            if node.val == destValue:
                dic[destValue] = res
                return 
            else:
                if node.left:
                    dfs(node.left, res+'L', destValue, meet, dic)
                if node.right:
                    dfs(node.right, res+'R', destValue, meet, dic)
                if self.parent[node]:
                    dfs(self.parent[node], res+'U', destValue, meet, dic)
            
        
        dfs(startnode, '', destValue, set(), self.dic)
        return self.dic[destValue]

接下来写LCA版本的。找到LCA,LCA往左的全部改成“U”,右边的保持不变就好。作者自己注意:下次一定把LCA这个写法当作模版背下来。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
        
        lcanode = self.lca(root, startValue, destValue)
        que = collections.deque()
        res = ''
        startpath = ''
        destpath = ''
        que.append((lcanode, res))
       # print(que)
        
        while que:
            curnode, curpath = que.popleft()
            if curnode.val ==  startValue:
                startpath = curpath
                if destpath:break
                
            elif curnode.val == destValue:
                destpath = curpath
                if startpath:break
            if curnode.left:
                que.append((curnode.left, curpath + 'L'))
            if curnode.right:
                que.append((curnode.right, curpath + 'R'))
   
        for _ in range(len(startpath)):
            res += 'U'
        for char in destpath:
            res += char
        return res   
        
    def lca(self,node, left, right):
        if not node:return None
        if node.val in [ left, right]:
            return node
        leftpath = self.lca(node.left, left, right)
        rightpath = self.lca(node.right, left, right)
        
        if leftpath is None:
            return rightpath
        
        if rightpath is None:
            return leftpath
        
        return node
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值