LeetCode 102. Binary Tree Level Order Traversal
Posted 小丑进场
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 102. Binary Tree Level Order Traversal相关的知识,希望对你有一定的参考价值。
原题
Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).
For example:
Given binary tree[3,9,20,null,null,15,7]
,3 / 9 20 / 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
解题思路
思路一
- 先递归求出该树的深度,接着根据深度初始化结果的数组,最后通过递归,将每一层的值依次添加到答案中
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 递归方法 class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if root == None: return [] dep = self.depth(root) self.ret = [[] for i in range(dep)] self.helper(root, 0) return self.ret def helper(self, node, dep): if node == None: return self.ret[dep].append(node.val) self.helper(node.left, dep + 1) self.helper(node.right, dep + 1) def depth(self, node): if node == None: return 0 return max(self.depth(node.left), self.depth(node.right)) + 1
思路二
- 利用栈来实现,将每一层的节点压入栈中,然后通过迭代遍历出每一层节点中的值并加入答案中
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 迭代方法,栈 class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if root == None: return [] stack, ret = [root], [] while stack: level_value = [] next_level = [] for node in stack: level_value.append(node.val) if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) ret.append(level_value) stack = next_level return ret
以上是关于LeetCode 102. Binary Tree Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 102. Binary Tree Level Order Traversal
[LeetCode]题解(python):102- Binary Tree Level Order Traversal
LeetCode 102. Binary Tree Level Order Traversal
Leetcode 102. Binary Tree Level Order Traversal