LeetCode-3(非递归前中后序遍历)
来源:互联网 发布:淘宝上买steam游戏商家 编辑:程序博客网 时间:2024/05/20 16:14
一、Binary Tree Preorder Traversal
前序遍历(根 左 右),不使用递归
stack开始压入根,每次循环弹出stack最后一个节点p,
若p不为None
res记录值,stack依次压入p的右节点、左节点
class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res=[] stack=[] while stack or root: if root: stack.append(root) res.append(root.val) root=root.left else: root=stack.pop() root=root.right return res ################################################################ res=[] stack=[root] while stack: cur=stack.pop() if cur: res.append(cur.val) stack.append(cur.right) stack.append(cur.left) return res
二、Binary Tree Postorder Traversal
后序遍历(左 右 根),不使用递归
前序遍历改造, 根左右 => 根右左(反转)=> 左右根
class Solution(object): def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res=[] stack=[] while stack or root: if root: stack.append(root) res.insert(0,root.val) root=root.right else: root=stack.pop() root=root.left return res####################################################### res=[] stack=[root] while stack: cur=stack.pop() if cur: res.append(cur.val) stack.append(cur.left) stack.append(cur.right) return res[::-1]
三、Binary Tree Inorder Traversal
中序遍历(左 根 右),不使用递归
class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res=[] stack=[] while root or stack: if root: stack.append(root) root=root.left else: root=stack.pop() res.append(root.val) root=root.right return res
阅读全文
0 0
- LeetCode-3(非递归前中后序遍历)
- 非递归前中后序遍历
- 二叉树的非递归遍历 (leetcode)
- LeetCode:Binary Tree Traversal(二叉树遍历非递归)
- leetcode 二叉树遍历非递归实现
- 二叉树遍历(前中后序递归、非递归遍历,层次遍历,C++实现)
- 二叉树遍历——层次遍历、前中后序遍历(递归、非递归)
- 非递归前序遍历(非递归、非栈)
- leetcode 二叉树前序遍历的递归和非递归实现
- leetcode 二叉树中序遍历的递归和非递归实现
- 二叉树遍历(递归,非递归)
- 二叉树中序遍历(递归+非递归)
- 树的遍历(递归、非递归)
- 二叉树(前中后序递归非递归遍历,层次遍历,C++实现)
- 二叉树(前中后序递归非递归遍历,层次遍历
- 二叉树遍历(递归、非递归、Morris遍历)
- 二叉树遍历(递归、非递归、Morris遍历)
- 二叉树的遍历(递归+非递归+层次遍历)
- js: 单例模式
- 从0开始的WEB开发之路之SpringMVC篇——初识springMVC(1)
- 华为Easy-IP配置指南
- kaldi使用tri4b进行测试时的调参
- RK3399嵌入式开发板QT下wifi 移植方法
- LeetCode-3(非递归前中后序遍历)
- BigDecimal的定义和比较
- strStr II
- websocket断开重连解决方案,基于子慕大诗人博客修改 健壮强化版
- sklearn 精确率、召回率
- 我是被淘宝给气到了,不在使用这个玩意,泄露我的信息
- Java—API
- WebSocket connection to 'ws://localhost/aa/ws1' net::ERR_CONNECTION_REFUSED
- springmvc-annotation注解式开发(表单封装)