标签:new code fine bsp ack ini down 个数 mes
Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth.(e.g., if you have a tree with depth D, you‘ll have D linked lists)
这道题给定一个二叉树,要求我们对于每一层的节点建立链表。这里涉及几个数的概念,depth, height, level. 你能分得清楚吗?看以下的定义。
Height of node – The height of a node is the number of edges on the longest downward path between that node and a leaf.
Height of tree - The height of a tree is the number of edges on the longest downward path between the root and a leaf.
Depth –The depth of a node is the number of edges from the node to the tree‘s root node.
Level – The level of a node is defined by 1 + the number of connections between the node and the root.
这道题要求我们对tree的每一个depth的nodes建立个链表,实际上就是对数进行层序遍历,BFS是经典的层序遍历的方法,见如下代码:
class TreeNode attr_accessor :val, :left, :right def initialize(val) @val = val @left = nil @right = nil end end class LinkedListNode attr_accessor :val, :next def initialize(val) @val = val @next = nil end end def build_linked_lists(root) return [] if root.nil? lists = [] q = Queue.new q << root while !q.empty? size = q.size dummy = LinkedListNode.new(0) head = dummy size.times do front = q.pop head.next = LinkedListNode.new(front.val) head = head.next q << front.left if front.left q << front.right if front.right end lists << dummy.next end lists end
[Cracking the Coding Interview] 4.3 List of Depths
标签:new code fine bsp ack ini down 个数 mes
原文地址:https://www.cnblogs.com/infinitycoder/p/9186526.html