mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 04:31:55 +08:00
feat: Add Ruby code - chapter "computational complexity" (#1212)
* feat: add ruby code - chapter computational complexity * feat: add ruby code blocks
This commit is contained in:
@ -13,3 +13,46 @@ def print_linked_list(head)
|
||||
end
|
||||
puts "#{list.join(" -> ")}"
|
||||
end
|
||||
|
||||
class Trunk
|
||||
attr_accessor :prev, :str
|
||||
|
||||
def initialize(prev, str)
|
||||
@prev = prev
|
||||
@str = str
|
||||
end
|
||||
end
|
||||
|
||||
def show_trunk(p)
|
||||
return if p.nil?
|
||||
|
||||
show_trunk(p.prev)
|
||||
print p.str
|
||||
end
|
||||
|
||||
### 打印二叉树 ###
|
||||
# This tree printer is borrowed from TECHIE DELIGHT
|
||||
# https://www.techiedelight.com/c-program-print-binary-tree/
|
||||
def print_tree(root, prev=nil, is_right=false)
|
||||
return if root.nil?
|
||||
|
||||
prev_str = " "
|
||||
trunk = Trunk.new prev, prev_str
|
||||
print_tree root.right, trunk, true
|
||||
|
||||
if prev.nil?
|
||||
trunk.str = "———"
|
||||
elsif is_right
|
||||
trunk.str = "/———"
|
||||
prev_str = " |"
|
||||
else
|
||||
trunk.str = "\\———"
|
||||
prev.str = prev_str
|
||||
end
|
||||
|
||||
show_trunk trunk
|
||||
puts " #{root.val}"
|
||||
prev.str = prev_str if prev
|
||||
trunk.str = " |"
|
||||
print_tree root.left, trunk, false
|
||||
end
|
||||
|
||||
18
codes/ruby/utils/tree_node.rb
Normal file
18
codes/ruby/utils/tree_node.rb
Normal file
@ -0,0 +1,18 @@
|
||||
=begin
|
||||
File: tree_node.rb
|
||||
Created Time: 2024-03-30
|
||||
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
|
||||
=end
|
||||
|
||||
### 二叉树节点类 ###
|
||||
class TreeNode
|
||||
attr_accessor :val # 节点值
|
||||
attr_accessor :height # 节点高度
|
||||
attr_accessor :left # 左子节点引用
|
||||
attr_accessor :right # 右子节点引用
|
||||
|
||||
def initialize(val=0)
|
||||
@val = val
|
||||
@height = 0
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user