[Cracking the Coding Interview] 4.3 List of Depths

Posted infinitycoder

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Cracking the Coding Interview] 4.3 List of Depths相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

Cracking the Coding Interview

Cracking the Coding Interview 第二章

[Cracking the Coding Interview] 4.3 List of Depths

[Cracking the Coding Interview] 4.2 Minimal Tree 最小树

[Cracking the Coding Interview] 4.5 Validate BST

Cracking the Coding Interview, Binary Tree, Binary Search Tress