当前位置:   article > 正文

Leetcode -二叉树_leetcode二叉树

leetcode二叉树

https://github.com/LongxingTan/Machine-learning-interview

由于平时喜欢用LGB做数据挖掘,所以就先从二叉树开始熟悉一下leetcode。本文总结一下leetcode的二叉树类型

方法

  • 有时候可以试一下递归和非递归方法,递归转化为非递归需要手工保存一个栈
  • 二叉搜索树利用其特点中序遍历是排序的
  • 任何题目还是要从简单或暴力解法做起

模版

  • 单root
  • 双root

树的遍历

主要是前中后、层序遍历

树的生成/构建

此类题目返回的是一棵树。构建时需要先构建root,再left 和right。
那么构建linked list的题目其实就是构建node和next。但是在已有树时,可以从tail或top

典型题目从preorder和inorder恢复二叉树等。

106中,虽然注意了递归。也要却要注意先生成右子树,再生成左子树的顺序,否则报错节点不存在。因为写法里有关于后续的pop,只有右子树的pop完之后剩下的才都是左子树节点

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        if not inorder or not postorder:
            return        
 
        root = TreeNode(postorder.pop(-1))
        index = inorder.index(root.val)
        root.right = self.buildTree(inorder[index+1:], postorder)
        root.left = self.buildTree(inorder[: index], postorder)
        
        return root
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

这题还是很综合的,有树的构建、有BST、还有类似回溯的permuattion。

树的递归

此类题目用的是dfs或回溯在树中的应用

BST性质

还有一类是针对BST中序的题目。有时候先遍历完根据排序性质判断反而更简单,在遍历过程中进行操作比较难想

参考

  • https://www.zhihu.com/question/280279208
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/656006
推荐阅读
相关标签
  

闽ICP备14008679号