zoukankan      html  css  js  c++  java
  • LeetCode 102. 二叉树的层序遍历

    给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
    
     
    
    示例:
    二叉树:[3,9,20,null,null,15,7],
    
        3
       / 
      9  20
        /  
       15   7
    返回其层次遍历结果:
    
    [
      [3],
      [9,20],
      [15,7]
    ]
    
    class Solution(object):
    	def levelOrder(self, root):
    		"""
    		:type root: TreeNode
    		:rtype: List[List[int]]
    		"""
    		if not root:
    			return []
    		res = []
    		queue = [root]
    		while queue:
    			# 获取当前队列的长度,这个长度相当于 当前这一层的节点个数
    			size = len(queue)
    			tmp = []
    			# 将队列中的元素都拿出来(也就是获取这一层的节点),放到临时list中
    			# 如果节点的左/右子树不为空,也放入队列中
    			for _ in xrange(size):
    				r = queue.pop(0)
    				tmp.append(r.val)
    				if r.left:
    					queue.append(r.left)
    				if r.right:
    					queue.append(r.right)
    			# 将临时list加入最终返回结果中
    			res.append(tmp)
    		return res
    
    class Solution(object):
    	def levelOrder(self, root):
    		"""
    		:type root: TreeNode
    		:rtype: List[List[int]]
    		"""
    		if not root:
    			return []
    		res = []
    		def dfs(index,r):
    			# 假设res是[ [1],[2,3] ], index是3,就再插入一个空list放到res中
    			if len(res)<index:
    				res.append([])
    			#  将当前节点的值加入到res中,index代表当前层,假设index是3,节点值是99
    			# res是[ [1],[2,3] [4] ],加入后res就变为 [ [1],[2,3] [4,99] ]
    			res[index-1].append(r.val)
    			# 递归的处理左子树,右子树,同时将层数index+1
    			if r.left:
    				dfs(index+1,r.left)
    			if r.right:
    				dfs(index+1,r.right)
    		dfs(1,root)
    		return res
    
    
    
  • 相关阅读:
    The executable was signed with invalid entitlements
    iOS7 文本转语音 AVSpeechSynthesizer
    The document "ViewController.xib" could not be opened. Could not read archive.
    UIPanGestureRecognizer
    UINavigationController
    IE6下面的css调试工具
    15款最好的网站音乐播放器
    ASP.NET常用加密解密方法
    ASP.NET根据IP获取省市地址
    强悍的CSS工具组合:Blueprint, Sass, Compass
  • 原文地址:https://www.cnblogs.com/sandy-t/p/13338868.html
Copyright © 2011-2022 走看看