[LeetCode][JavaScript]Invert Binary Tree 反转二叉树

雨点打透心脏的1/2处 2022-01-20 00:31 271阅读 0赞

反转二叉树

  • 其实我从没有想到前端面试会问到这个问题,题目来源于google的面试

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off. (我们90%的工程师都用你写的软件但是我们不能聘用你)

吊吊吊,著名homebrew的初创者Howell前往google面试ios开发,结果还没问到ios技术问题的时候就已经挂了,而且死在反转二叉树,有那么点意思。果然title在我g厂面试还是渣渣,我g厂从不缺title

我这个代码也是在网上看到的,直接抄过来的知乎

  1. class Solution:
  2. # @param {TreeNode} root
  3. # @return {TreeNode}
  4. def invertTree(self, root):
  5. from Queue import Queue
  6. q = Queue()
  7. q.put(root)
  8. while not q.empty():
  9. node = q.get()
  10. if not node:
  11. continue
  12. node.left, node.right = node.right, node.left
  13. if node.left:
  14. q.put(node.left)
  15. if node.right:
  16. q.put(node.right)
  17. return root
  18. 复制代码

这个类写的老夫懵逼了,老夫在git上看到一个简单一点的方法,顺便也贴出来把

  1. function binaryTree(node) {
  2. if(!node) return
  3. let left = binaryTree(node.left)
  4. let right = binaryTree(node.right)
  5. if(left) node.left = right
  6. if(right) node.right = left
  7. return node
  8. }
  9. 复制代码

突然想到可能很多同学对二叉树没什么概念,我就把这个类似的树写出来吧

  1. let tree = {
  2. left: {
  3. left: {
  4. value: 1
  5. },
  6. right: {
  7. value: 2
  8. },
  9. value: 3
  10. },
  11. right: {
  12. left: {
  13. value: 6
  14. },
  15. right: {
  16. value: 7
  17. },
  18. value: 8
  19. },
  20. value: 10
  21. }
  22. 复制代码

发表评论

表情:
评论列表 (有 0 条评论,271人围观)

还没有评论,来说两句吧...

相关阅读