码迷,mamicode.com
首页 > 其他好文 > 详细

[Cracking the Coding Interview] 4.3 List of Depths

时间:2018-06-16 01:01:26      阅读:144      评论:0      收藏:0      [点我收藏+]

标签: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.

  • 从node到leaf会有多条路径,最长的路径的边的条数是这个node的height。

Height of tree - The height of a tree is the number of edges on the longest downward path between the root and a leaf.

  • 所以有 the height of a tree is the height of its root.
  • 我们经常会问这样的问题:what is the max number of nodes a tree can have if the height of the tree is h?Answer: 2^h - 1

Depth –The depth of a node is the number of edges from the node to the tree‘s root node.

  • Depth 和 Height比是方向相反的,Height是以leaf为基准,而Depth以root为基准
  • depth of root is 0.

Level – The level of a node is defined by 1 + the number of connections between the node and the root.

  • level = depth + 1
  • 要注意level从1开始,depth从0开始!!

这道题要求我们对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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!