二叉树回顾
来源:互联网 发布:淘宝雷锋侠怎么看 编辑:程序博客网 时间:2024/06/05 05:16
遍历:
前序遍历: 节点-左-右
使用一个栈来实现,非递归:
class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root:return [] answer=[] mystack=[root] while mystack: now=mystack.pop() answer.append(now.val) if now.right:mystack.append(now.right) if now.left:mystack.append(now.left) return answer
嗯,写的麻烦了,判断非空,然后直接append就好了;
def preorderTraversal(self, root): ret = [] stack = [root] while stack: node = stack.pop() if node: ret.append(node.val) stack.append(node.right) stack.append(node.left) return ret
后续遍历:左、右、结点
我的思路还是用一个栈来实现,但是这个时候 节点 应该插入在第一位。出栈顺序是 右节点,再是左节点。
class Solution(object): def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ ret = [] stack = [root] while stack: node = stack.pop() if node: ret=[node.val]+ret stack.append(node.left) stack.append(node.right) return ret
中序遍历:左、节点、右
直接看的好理解的 discuss,就是设置一个标记位:
class Solution: def inorderTraversal(self, root): stack = [ (False, root) ] acc = [] while stack: flag, val = stack.pop() if val: if not flag: stack.append( (False, val.right) ) stack.append( (True, val) ) stack.append( (False, val.left) ) else: acc.append( val.val ) return acc
层序遍历:
class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] ans,level=[],[root] while level: n,tem=[],[] for i in level: n.append(i.val) tem.extend([i.left,i.right]) ans.append(n) level=[j for j in tem if j] return ans
从低向上的层序遍历:
class Solution(object): def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] ans,level=[],[root] while level: n,tem=[],[] for i in level: n.append(i.val) tem.extend([i.left,i.right]) ans=[n]+ans level=[j for j in tem if j] return ans
求树的层数:104. Maximum Depth of Binary Tree
class Solution(object): def maxDepth(self, root): if not root: return 0 if not root.left and not root.right: return 1 return 1+max(self.maxDepth(root.left),self.maxDepth(root.right))class Solution(object): def maxDepth(self, root): stack=[(root,0)] level=0 while stack: p=stack.pop() if p[0]: level=max(level,p[1]+1) stack.extend([(p[0].left,p[1]+1),(p[0].right,p[1]+1)]) return level
0 0
- 【数据结构】回顾二叉树
- 二叉树回顾
- 数据结构快速回顾——二叉树
- 回顾二叉树,采用增加线索确定根节点
- 数据结构快速回顾——二叉查找树
- 二叉树回顾(1):建立、交换左右子树
- C/C++ 知识回顾 比较二叉树、拓扑排序
- 数据结构快速回顾——二叉树 解幂子集问题
- 数据结构回顾和总结(二叉搜索树(BST)的基本操作)
- 数据结构系统回顾与总结(3)(判断是否为同一棵二叉搜索树)
- 树知识回顾
- 数据结构-树的回顾
- 回顾
- 回顾
- 回顾
- 回顾
- 回顾
- 回顾
- Android Paint、Canvas、Matrix使用讲解(一、Paint)
- Windows intallij 配置storm项目
- 正则化与交叉验证
- 经典算法题每日演练——第四题 最长公共子序列
- python学习笔记4--函数
- 二叉树回顾
- 萌萌哒的第六题
- WEB服务器原理
- 使用解决方案资源管理器
- Sphinx+PHP+Mysql高效搜索web端搭建(windows)
- 几种提升工作效率的Eclipse使用技巧
- 判断用户输入的一个整数是否在以已知数组中
- maven打包出现com.sun.image.codec.jpeg does not exist报错
- 程序的机器级表示