python剑指offer系列把二叉树打印成多行
2018-03-02 15:12
507 查看
题目:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路:
按层遍历,遍历完每层后更新
solution:# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Print(self, pRoot):
if not pRoot:
return []
nodeStack = [pRoot]
result = []
while nodeStack:
res = []
nextStack = []
for i in nodeStack:
res.append(i.val)
if i.left:
nextStack.append(i.left)
if i.right:
nextStack.append(i.right)
nodeStack = nextStack
result.append(res)
return result
# write code here
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路:
按层遍历,遍历完每层后更新
solution:# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Print(self, pRoot):
if not pRoot:
return []
nodeStack = [pRoot]
result = []
while nodeStack:
res = []
nextStack = []
for i in nodeStack:
res.append(i.val)
if i.left:
nextStack.append(i.left)
if i.right:
nextStack.append(i.right)
nodeStack = nextStack
result.append(res)
return result
# write code here
相关文章推荐
- 剑指offer之把二叉树打印成多行(Python)
- python剑指offer系列按之字形顺序打印二叉树
- 剑指offer系列之五十五:把二叉树打印成多行
- 剑指Offer系列---(25)从上往下打印二叉树
- (剑指offer)把二叉树打印成多行
- 剑指offer系列之58:按之字形顺序打印二叉树
- 剑指offer-把二叉树打印成多行
- Python:把二叉树打印成多行
- 剑指Offer--把二叉树打印成多行
- python剑指offer系列通过求二叉树的深度来理解递归
- 剑指offer-把二叉树打印成多行
- python实现剑指offer系列:重建二叉树
- 剑指offer:把二叉树打印成多行
- python剑指offer系列二叉树的下一个节点
- 剑指offer——面试题60:把二叉树打印成多行
- python剑指offer系列二叉树中和为某一值的路径
- 剑指offer—把二叉树打印成多行
- 剑指Offer——把二叉树打印成多行
- 《剑指offer》把二叉树打印成多行
- python 实现剑指offer系列3:从尾到头打印链表