楼主: 李浩泉
跳转到指定楼层
上一主题 下一主题
收起左侧

[Leetcode] LC Python 刷题笔记 有志者事竟成

   
🔗
 楼主| 李浩泉 2020-8-1 03:57:10 | 只看该作者
全局:
LC上标的是中等难度,但是也是简单的基础概念,需要二叉树遍历

# 199 Binary Tree Right Side View


  1. '''
  2. Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

  3. Example:

  4. Input: [1,2,3,null,5,null,4]
  5. Output: [1, 3, 4]
  6. Explanation:

  7.    1            <---
  8. /   \
  9. 2     3         <---
  10. \     \
  11.   5     4       <---
  12. '''

  13. def rightSideView(self, root: TreeNode) -> List[int]:
  14.     if not root : return []
  15.     result = []
  16.     current = []
  17.     current.append(root)

  18.     while current :
  19.         next_level = []
  20.         value = []
  21.         for n in current :
  22.             value.append(n.val)
  23.             if n.right :
  24.                 next_level.append(n.right)
  25.             if n.left :
  26.                 next_level.append(n.left)
  27.             current = next_level
  28.         result.append(value)
  29.         
  30.     s = []
  31.     for i in range(len(result)):
  32.         s.append(result[i][0])
  33.     return s
复制代码


回复

使用道具 举报

🔗
 楼主| 李浩泉 2020-8-1 04:11:24 | 只看该作者
全局:
# 671 Second Minimum Node In a Binary Tree

一样的方法,先遍历出所有的值,然后从中找出第二小的值。不一定是最优解,但是是最容易理解和在面试时快速做出来不出错的方法之一。


  1. '''
  2. Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds.

  3. Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.

  4. If no such second minimum value exists, output -1 instead.

  5. Example 1:

  6. Input:
  7.     2
  8.    / \
  9.   2   5
  10.      / \
  11.     5   7

  12. Output: 5
  13. Explanation: The smallest value is 2, the second smallest value is 5.


  14. Example 2:

  15. Input:
  16.     2
  17.    / \
  18.   2   2

  19. Output: -1
  20. Explanation: The smallest value is 2, but there isn't any second smallest value.
  21. '''

  22. def findSecondMinimumValue(self, root: TreeNode) -> int:
  23.     if not root: return -1
  24.     result = []
  25.     current = []
  26.     current.append(root)
  27.         
  28.     while current:
  29.         next_level = []
  30.         for n in current:
  31.             result.append(n.val)
  32.             if n.left:
  33.                 next_level.append(n.left)
  34.             if n.right:
  35.                 next_level.append(n.right)
  36.             current = next_level
  37.                
  38.     s = set(result)
  39.     l = list(s)
  40.     l.sort()
  41.     if len(l) > 1 : return l[1]
  42.     else: return -1
复制代码


回复

使用道具 举报

全局:
你把进大厂看的太简单了。刷题只是过code那一轮,还有系统设计。两手都要抓,两手都要硬。
回复

使用道具 举报

🔗
 楼主| 李浩泉 2020-8-1 04:15:54 | 只看该作者
全局:
二叉树基础操作 - 遍历

1. Not Layer by Layer

  1. if not root: return []
  2.     result = []
  3.     current = []
  4.     current.append(root)
  5.         
  6.     while current:
  7.         next_level = []
  8.         for n in current:
  9.             result.append(n.val)
  10.             if n.left:
  11.                 next_level.append(n.left)
  12.             if n.right:
  13.                 next_level.append(n.right)
  14.             current = next_level
  15.     return result
复制代码




2. Layer by Layer


  1. if not root: return []
  2.     result = []
  3.     current = []
  4.     current.append(root)
  5.         
  6.     while current:
  7.         next_level = []
  8.         value = []
  9.         for n in current:
  10.             value.append(n.val)
  11.             if n.left:
  12.                 next_level.append(n.left)
  13.             if n.right:
  14.                 next_level.append(n.right)
  15.             current = next_level
  16.         result.append(value)
  17.     return result
复制代码


回复

使用道具 举报

🔗
niuhj 2020-8-1 04:24:24 | 只看该作者
全局:
可以啊,不过平推真的不适合啊,最好是按topic先刷,再随机平推检验
回复

使用道具 举报

🔗
 楼主| 李浩泉 2020-8-1 09:03:02 | 只看该作者
全局:
本帖最后由 李浩泉 于 2020-8-1 09:11 编辑

二叉树基础题里面另外一类就是:构建子函数,用 Recursion 递归

# 543 Diameter of Binary Tree


Complexity Analysis

Time Complexity: I visit every node once, so it is O(N).

Space Complexity: O(N).


  1. '''
  2. Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

  3. Example:
  4. Given a binary tree
  5.           1
  6.          / \
  7.         2   3
  8.        / \     
  9.       4   5   
  10. Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

  11. Note: The length of path between two nodes is represented by the number of edges between them.
  12. '''

  13. def diameterOfBinaryTree(self, root):
  14.     def longpath(y):
  15.         if not y : return 0
  16.         r = longpath(y.right)
  17.         l = longpath(y.left)
  18.         self.result = max(self.result, r + l + 1 )
  19.         return max(l,r) + 1
  20.         
  21.     self.result = 1
  22.     longpath(root)
  23.     return self.result - 1
复制代码




回复

使用道具 举报

🔗
 楼主| 李浩泉 2020-8-2 03:25:58 | 只看该作者
全局:

二叉树里面用递归的还有一种就是,不设子函数,就是用self,自己call自己,我也是看了答案之后,才敢用的。

# 235 Lowest Common Ancestor of a Binary Search Tree


  1. '''
  2. Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

  3. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

  4. Given binary search tree:  root = [6,2,8,0,4,7,9,null,null,3,5]

  5. Example 1:

  6. Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
  7. Output: 6
  8. Explanation: The LCA of nodes 2 and 8 is 6.
  9. '''

  10. def lowestCommonAncestor(self,root,p,q):
  11.     if not root: return root
  12.     if root.val == p.val or root.val == q.val:
  13.         return root
  14.     l = self.lowestCommonAncestor(root.left, p, q)
  15.     r = self.lowestCommonAncestor(root.right, p, q)
  16.     if l and r:
  17.         return root
  18.     return l or r
复制代码



回复

使用道具 举报

🔗
 楼主| 李浩泉 2020-8-2 03:33:33 | 只看该作者
全局:


# 236 Lowest Common Ancestor of a Binary Tree

和235一样,用self去做


  1. '''
  2. Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

  3. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

  4. Given the following binary tree:  root = [3,5,1,6,2,0,8,null,null,7,4]

  5. Example 1:

  6. Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
  7. Output: 3
  8. Explanation: The LCA of nodes 5 and 1 is 3.
  9. '''

  10. def lowestCommonAncestor(self, root, p, q):
  11.     if not root: return root
  12.     if root.val == p.val or root.val == q.val:
  13.         return root
  14.     l = self.lowestCommonAncestor(root.left, p, q)
  15.     r = self.lowestCommonAncestor(root.right, p, q)
  16.     if l and r:
  17.         return root
  18.     return l or r
复制代码




如果不用self去做,下面这个方法就比较难了



  1. def lowestCommonAncestor(self, root, p, q):
  2.     stack = [root]
  3.     parent = {root: None}
  4.     while p not in parent or q not in parent:
  5.         node = stack.pop()
  6.         if node.left:
  7.             parent[node.left] = node
  8.             stack.append(node.left)
  9.         if node.right:
  10.             parent[node.right] = node
  11.             stack.append(node.right)
  12.     ancestors = set()
  13.     while p:
  14.         ancestors.add(p)
  15.         p = parent[p]
  16.     while q not in ancestors:
  17.         q = parent[q]
  18.     return q
复制代码


回复

使用道具 举报

🔗
 楼主| 李浩泉 2020-8-2 05:05:34 | 只看该作者
全局:
# 257 Binary Tree Paths

这道题太经典了,构建子函数递归Recursion,然后在子函数内部继续call子函数自己。


  1. '''
  2. Given a binary tree, return all root-to-leaf paths.

  3. Note: A leaf is a node with no children.

  4. Example:

  5. Input:

  6.    1
  7. /   \
  8. 2     3
  9. \
  10.   5

  11. Output: ["1->2->5", "1->3"]

  12. Explanation: All root-to-leaf paths are: 1->2->5, 1->3
  13. '''

  14. def binaryTreePaths(self, root: TreeNode) -> List[str]:
  15.     def construct_paths(root, path):
  16.         if root:
  17.             path += str(root.val)
  18.             if not root.left and not root.right:  # if reach a leaf
  19.                 paths.append(path)  # update paths  
  20.             else:
  21.                 path += '->'  # extend the current path
  22.                 construct_paths(root.left, path)
  23.                 construct_paths(root.right, path)
  24.     paths = []
  25.     construct_paths(root, '')
  26.     return paths
复制代码


回复

使用道具 举报

🔗
 楼主| 李浩泉 2020-8-2 05:23:31 | 只看该作者
全局:

# 700 Search in a Binary Search Tree

同样的方法,call self.****,然后递归。

  1. '''
  2. Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL.

  3. For example,

  4. Given the tree:
  5.         4
  6.        / \
  7.       2   7
  8.      / \
  9.     1   3

  10. And the value to search: 2
  11. You should return this subtree:

  12.       2     
  13.      / \   
  14.     1   3
  15. In the example above, if we want to search the value 5, since there is no node with value 5, we should return NULL.

  16. Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null.
  17. '''

  18. def searchBST(self, root: TreeNode, val: int) -> TreeNode:
  19.     if root is None or val == root.val:
  20.         return root
  21.     if val < root.val:
  22.         return self.searchBST(root.left, val)
  23.     else:
  24.         return self.searchBST(root.right, val)
复制代码



回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表