feat: add ruby code blocks - chapter tree (#1293)

pull/1297/head
khoaxuantu 7 months ago committed by GitHub
parent 587344da62
commit 74f1a63e8c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -123,7 +123,9 @@
=== "Ruby" === "Ruby"
```ruby title="" ```ruby title=""
### 二叉树的数组表示 ###
# 使用 nil 来表示空位
tree = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15]
``` ```
=== "Zig" === "Zig"

@ -129,9 +129,9 @@ AVL 树既是二叉搜索树,也是平衡二叉树,同时满足这两类二
right: TreeNode | null; // 右子节点指针 right: TreeNode | null; // 右子节点指针
constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) { constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val; this.val = val === undefined ? 0 : val;
this.height = height === undefined ? 0 : height; this.height = height === undefined ? 0 : height;
this.left = left === undefined ? null : left; this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right; this.right = right === undefined ? null : right;
} }
} }
``` ```
@ -214,7 +214,18 @@ AVL 树既是二叉搜索树,也是平衡二叉树,同时满足这两类二
=== "Ruby" === "Ruby"
```ruby title="" ```ruby title=""
### AVL 树节点类 ###
class TreeNode
attr_accessor :val # 节点值
attr_accessor :height # 节点高度
attr_accessor :left # 左子节点引用
attr_accessor :right # 右子节点引用
def initialize(val)
@val = val
@height = 0
end
end
``` ```
=== "Zig" === "Zig"

@ -106,7 +106,7 @@
val: number; val: number;
left: TreeNode | null; left: TreeNode | null;
right: TreeNode | null; right: TreeNode | null;
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val; // 节点值 this.val = val === undefined ? 0 : val; // 节点值
this.left = left === undefined ? null : left; // 左子节点引用 this.left = left === undefined ? null : left; // 左子节点引用
@ -189,7 +189,16 @@
=== "Ruby" === "Ruby"
```ruby title="" ```ruby title=""
### 二叉树节点类 ###
class TreeNode
attr_accessor :val # 节点值
attr_accessor :left # 左子节点引用
attr_accessor :right # 右子节点引用
def initialize(val)
@val = val
end
end
``` ```
=== "Zig" === "Zig"
@ -432,7 +441,18 @@
=== "Ruby" === "Ruby"
```ruby title="binary_tree.rb" ```ruby title="binary_tree.rb"
# 初始化二叉树
# 初始化节点
n1 = TreeNode.new(1)
n2 = TreeNode.new(2)
n3 = TreeNode.new(3)
n4 = TreeNode.new(4)
n5 = TreeNode.new(5)
# 构建节点之间的引用(指针)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
``` ```
=== "Zig" === "Zig"
@ -594,7 +614,13 @@
=== "Ruby" === "Ruby"
```ruby title="binary_tree.rb" ```ruby title="binary_tree.rb"
# 插入与删除节点
_p = TreeNode.new(0)
# 在 n1 -> n2 中间插入节点 _p
n1.left = _p
_p.left = n2
# 删除节点
n1.left = n2
``` ```
=== "Zig" === "Zig"

Loading…
Cancel
Save