This commit is contained in:
krahets
2025-12-31 19:37:45 +08:00
parent 29ec0c699d
commit 3c9d5689c4
279 changed files with 40895 additions and 16087 deletions
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+52 -42
View File
@@ -2,9 +2,9 @@
comments: true
---
# 7.1   Binary tree
# 7.1   Binary Tree
A <u>binary tree</u> is a non-linear data structure that represents the hierarchical relationship between ancestors and descendants and embodies the divide-and-conquer logic of "splitting into two". Similar to a linked list, the basic unit of a binary tree is a node, and each node contains a value, a reference to its left child node, and a reference to its right child node.
A <u>binary tree</u> is a non-linear data structure that represents the derivation relationship between "ancestors" and "descendants" and embodies the divide-and-conquer logic of "one divides into two". Similar to a linked list, the basic unit of a binary tree is a node, and each node contains a value, a reference to its left child node, and a reference to its right child node.
=== "Python"
@@ -193,13 +193,16 @@ A <u>binary tree</u> is a non-linear data structure that represents the hierarch
=== "Ruby"
```ruby title=""
### Binary tree node class ###
class TreeNode
attr_accessor :val # Node value
attr_accessor :left # Reference to left child node
attr_accessor :right # Reference to right child node
```
=== "Zig"
```zig title=""
def initialize(val)
@val = val
end
end
```
Each node has two references (pointers), pointing respectively to the <u>left-child node</u> and <u>right-child node</u>. This node is called the <u>parent node</u> of these two child nodes. When given a node of a binary tree, we call the tree formed by this node's left child and all nodes below it the <u>left subtree</u> of this node. Similarly, the <u>right subtree</u> can be defined.
@@ -210,7 +213,7 @@ Each node has two references (pointers), pointing respectively to the <u>left-ch
<p align="center"> Figure 7-1 &nbsp; Parent Node, child Node, subtree </p>
## 7.1.1 &nbsp; Common terminology of binary trees
## 7.1.1 &nbsp; Common Terminology of Binary Trees
The commonly used terminology of binary trees is shown in Figure 7-2.
@@ -231,9 +234,9 @@ The commonly used terminology of binary trees is shown in Figure 7-2.
Please note that we usually define "height" and "depth" as "the number of edges traversed", but some questions or textbooks may define them as "the number of nodes traversed". In this case, both height and depth need to be incremented by 1.
## 7.1.2 &nbsp; Basic operations of binary trees
## 7.1.2 &nbsp; Basic Operations of Binary Trees
### 1. &nbsp; Initializing a binary tree
### 1. &nbsp; Initializing a Binary Tree
Similar to a linked list, the initialization of a binary tree involves first creating the nodes and then establishing the references (pointers) between them.
@@ -440,20 +443,26 @@ Similar to a linked list, the initialization of a binary tree involves first cre
=== "Ruby"
```ruby title="binary_tree.rb"
# Initializing a binary tree
# Initializing nodes
n1 = TreeNode.new(1)
n2 = TreeNode.new(2)
n3 = TreeNode.new(3)
n4 = TreeNode.new(4)
n5 = TreeNode.new(5)
# Linking references (pointers) between nodes
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
```
=== "Zig"
??? pythontutor "Code Visualization"
```zig title="binary_tree.zig"
<div style="height: 549px; width: 100%;"><iframe class="pythontutor-iframe" src="https://pythontutor.com/iframe-embed.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&codeDivHeight=472&codeDivWidth=350&cumulative=false&curInstr=3&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe></div>
<div style="margin-top: 5px;"><a href="https://pythontutor.com/iframe-embed.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&codeDivHeight=800&codeDivWidth=600&cumulative=false&curInstr=3&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false" target="_blank" rel="noopener noreferrer">Full Screen ></a></div>
```
??? pythontutor "Code visualization"
https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
### 2. &nbsp; Inserting and removing nodes
### 2. &nbsp; Inserting and Removing Nodes
Similar to a linked list, inserting and removing nodes in a binary tree can be achieved by modifying pointers. Figure 7-3 provides an example.
@@ -604,28 +613,29 @@ Similar to a linked list, inserting and removing nodes in a binary tree can be a
=== "Ruby"
```ruby title="binary_tree.rb"
# Inserting and removing nodes
_p = TreeNode.new(0)
# Inserting node _p between n1 and n2
n1.left = _p
_p.left = n2
# Removing node _p
n1.left = n2
```
=== "Zig"
??? pythontutor "Code Visualization"
```zig title="binary_tree.zig"
```
??? pythontutor "Code visualization"
https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E6%8F%92%E5%85%A5%E4%B8%8E%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%E5%9C%A8%20n1%20-%3E%20n2%20%E4%B8%AD%E9%97%B4%E6%8F%92%E5%85%A5%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
<div style="height: 549px; width: 100%;"><iframe class="pythontutor-iframe" src="https://pythontutor.com/iframe-embed.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E6%8F%92%E5%85%A5%E4%B8%8E%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%E5%9C%A8%20n1%20-%3E%20n2%20%E4%B8%AD%E9%97%B4%E6%8F%92%E5%85%A5%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20n2&codeDivHeight=472&codeDivWidth=350&cumulative=false&curInstr=37&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe></div>
<div style="margin-top: 5px;"><a href="https://pythontutor.com/iframe-embed.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E6%8F%92%E5%85%A5%E4%B8%8E%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%E5%9C%A8%20n1%20-%3E%20n2%20%E4%B8%AD%E9%97%B4%E6%8F%92%E5%85%A5%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20n2&codeDivHeight=800&codeDivWidth=600&cumulative=false&curInstr=37&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false" target="_blank" rel="noopener noreferrer">Full Screen ></a></div>
!!! tip
It should be noted that inserting nodes may change the original logical structure of the binary tree, while removing nodes typically involves removing the node and all its subtrees. Therefore, in a binary tree, insertion and removal are usually performed through a set of operations to achieve meaningful outcomes.
## 7.1.3 &nbsp; Common types of binary trees
## 7.1.3 &nbsp; Common Types of Binary Trees
### 1. &nbsp; Perfect binary tree
### 1. &nbsp; Perfect Binary Tree
As shown in Figure 7-4, in a <u>perfect binary tree</u>, all levels are completely filled with nodes. In a perfect binary tree, leaf nodes have a degree of $0$, while all other nodes have a degree of $2$. The total number of nodes can be calculated as $2^{h+1} - 1$, where $h$ is the height of the tree. This exhibits a standard exponential relationship, reflecting the common phenomenon of cell division in nature.
As shown in Figure 7-4, a <u>perfect binary tree</u> has all levels completely filled with nodes. In a perfect binary tree, leaf nodes have a degree of $0$, while all other nodes have a degree of $2$. If the tree height is $h$, the total number of nodes is $2^{h+1} - 1$, exhibiting a standard exponential relationship that reflects the common phenomenon of cell division in nature.
!!! tip
@@ -635,23 +645,23 @@ As shown in Figure 7-4, in a <u>perfect binary tree</u>, all levels are complete
<p align="center"> Figure 7-4 &nbsp; Perfect binary tree </p>
### 2. &nbsp; Complete binary tree
### 2. &nbsp; Complete Binary Tree
As shown in Figure 7-5, a <u>complete binary tree</u> is a binary tree where only the bottom level is possibly not completely filled, and nodes at the bottom level must be filled continuously from left to right. Note that a perfect binary tree is also a complete binary tree.
As shown in Figure 7-5, a <u>complete binary tree</u> only allows the bottom level to be incompletely filled, and the nodes at the bottom level must be filled continuously from left to right. Note that a perfect binary tree is also a complete binary tree.
![Complete binary tree](binary_tree.assets/complete_binary_tree.png){ class="animation-figure" }
<p align="center"> Figure 7-5 &nbsp; Complete binary tree </p>
### 3. &nbsp; Full binary tree
### 3. &nbsp; Full Binary Tree
As shown in Figure 7-6, a <u>full binary tree</u>, except for the leaf nodes, has two child nodes for all other nodes.
As shown in Figure 7-6, in a <u>full binary tree</u>, all nodes except leaf nodes have two child nodes.
![Full binary tree](binary_tree.assets/full_binary_tree.png){ class="animation-figure" }
<p align="center"> Figure 7-6 &nbsp; Full binary tree </p>
### 4. &nbsp; Balanced binary tree
### 4. &nbsp; Balanced Binary Tree
As shown in Figure 7-7, in a <u>balanced binary tree</u>, the absolute difference between the height of the left and right subtrees of any node does not exceed 1.
@@ -659,12 +669,12 @@ As shown in Figure 7-7, in a <u>balanced binary tree</u>, the absolute differenc
<p align="center"> Figure 7-7 &nbsp; Balanced binary tree </p>
## 7.1.4 &nbsp; Degeneration of binary trees
## 7.1.4 &nbsp; Degeneration of Binary Trees
Figure 7-8 shows the ideal and degenerate structures of binary trees. A binary tree becomes a "perfect binary tree" when every level is filled; while it degenerates into a "linked list" when all nodes are biased toward one side.
Figure 7-8 shows the ideal and degenerate structures of binary trees. When every level of a binary tree is filled, it reaches the "perfect binary tree" state; when all nodes are biased toward one side, the binary tree degenerates into a "linked list".
- A perfect binary tree is an ideal scenario where the "divide and conquer" advantage of a binary tree can be fully utilized.
- On the other hand, a linked list represents another extreme where all operations become linear, resulting in a time complexity of $O(n)$.
- A perfect binary tree is the ideal case, fully leveraging the "divide and conquer" advantage of binary trees.
- A linked list represents the other extreme, where all operations become linear operations with time complexity degrading to $O(n)$.
![The Best and Worst Structures of Binary Trees](binary_tree.assets/binary_tree_best_worst_cases.png){ class="animation-figure" }
+528 -95
View File
@@ -2,25 +2,25 @@
comments: true
---
# 7.2 &nbsp; Binary tree traversal
# 7.2 &nbsp; Binary Tree Traversal
From a physical structure perspective, a tree is a data structure based on linked lists. Hence, its traversal method involves accessing nodes one by one through pointers. However, a tree is a non-linear data structure, which makes traversing a tree more complex than traversing a linked list, requiring the assistance of search algorithms.
The common traversal methods for binary trees include level-order traversal, pre-order traversal, in-order traversal, and post-order traversal.
## 7.2.1 &nbsp; Level-order traversal
## 7.2.1 &nbsp; Level-Order Traversal
As shown in Figure 7-9, <u>level-order traversal</u> traverses the binary tree from top to bottom, layer by layer. Within each level, it visits nodes from left to right.
Level-order traversal is essentially a type of <u>breadth-first traversal</u>, also known as <u>breadth-first search (BFS)</u>, which embodies a "circumferentially outward expanding" layer-by-layer traversal method.
Level-order traversal is essentially <u>breadth-first traversal</u>, also known as <u>breadth-first search (BFS)</u>, which embodies a "expanding outward circle by circle" layer-by-layer traversal method.
![Level-order traversal of a binary tree](binary_tree_traversal.assets/binary_tree_bfs.png){ class="animation-figure" }
<p align="center"> Figure 7-9 &nbsp; Level-order traversal of a binary tree </p>
### 1. &nbsp; Code implementation
### 1. &nbsp; Code Implementation
Breadth-first traversal is usually implemented with the help of a "queue". The queue follows the "first in, first out" rule, while breadth-first traversal follows the "layer-by-layer progression" rule, the underlying ideas of the two are consistent. The implementation code is as follows:
Breadth-first traversal is typically implemented with the help of a "queue". The queue follows the "first in, first out" rule, while breadth-first traversal follows the "layer-by-layer progression" rule; the underlying ideas of the two are consistent. The implementation code is as follows:
=== "Python"
@@ -30,15 +30,15 @@ Breadth-first traversal is usually implemented with the help of a "queue". The q
# Initialize queue, add root node
queue: deque[TreeNode] = deque()
queue.append(root)
# Initialize a list to store the traversal sequence
# Initialize a list to save the traversal sequence
res = []
while queue:
node: TreeNode = queue.popleft() # Queue dequeues
node: TreeNode = queue.popleft() # Dequeue
res.append(node.val) # Save node value
if node.left is not None:
queue.append(node.left) # Left child node enqueues
queue.append(node.left) # Left child node enqueue
if node.right is not None:
queue.append(node.right) # Right child node enqueues
queue.append(node.right) # Right child node enqueue
return res
```
@@ -50,16 +50,16 @@ Breadth-first traversal is usually implemented with the help of a "queue". The q
// Initialize queue, add root node
queue<TreeNode *> queue;
queue.push(root);
// Initialize a list to store the traversal sequence
// Initialize a list to save the traversal sequence
vector<int> vec;
while (!queue.empty()) {
TreeNode *node = queue.front();
queue.pop(); // Queue dequeues
queue.pop(); // Dequeue
vec.push_back(node->val); // Save node value
if (node->left != nullptr)
queue.push(node->left); // Left child node enqueues
queue.push(node->left); // Left child node enqueue
if (node->right != nullptr)
queue.push(node->right); // Right child node enqueues
queue.push(node->right); // Right child node enqueue
}
return vec;
}
@@ -73,15 +73,15 @@ Breadth-first traversal is usually implemented with the help of a "queue". The q
// Initialize queue, add root node
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
// Initialize a list to store the traversal sequence
// Initialize a list to save the traversal sequence
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll(); // Queue dequeues
TreeNode node = queue.poll(); // Dequeue
list.add(node.val); // Save node value
if (node.left != null)
queue.offer(node.left); // Left child node enqueues
queue.offer(node.left); // Left child node enqueue
if (node.right != null)
queue.offer(node.right); // Right child node enqueues
queue.offer(node.right); // Right child node enqueue
}
return list;
}
@@ -90,85 +90,266 @@ Breadth-first traversal is usually implemented with the help of a "queue". The q
=== "C#"
```csharp title="binary_tree_bfs.cs"
[class]{binary_tree_bfs}-[func]{LevelOrder}
/* Level-order traversal */
List<int> LevelOrder(TreeNode root) {
// Initialize queue, add root node
Queue<TreeNode> queue = new();
queue.Enqueue(root);
// Initialize a list to save the traversal sequence
List<int> list = [];
while (queue.Count != 0) {
TreeNode node = queue.Dequeue(); // Dequeue
list.Add(node.val!.Value); // Save node value
if (node.left != null)
queue.Enqueue(node.left); // Left child node enqueue
if (node.right != null)
queue.Enqueue(node.right); // Right child node enqueue
}
return list;
}
```
=== "Go"
```go title="binary_tree_bfs.go"
[class]{}-[func]{levelOrder}
/* Level-order traversal */
func levelOrder(root *TreeNode) []any {
// Initialize queue, add root node
queue := list.New()
queue.PushBack(root)
// Initialize a slice to save traversal sequence
nums := make([]any, 0)
for queue.Len() > 0 {
// Dequeue
node := queue.Remove(queue.Front()).(*TreeNode)
// Save node value
nums = append(nums, node.Val)
if node.Left != nil {
// Left child node enqueue
queue.PushBack(node.Left)
}
if node.Right != nil {
// Right child node enqueue
queue.PushBack(node.Right)
}
}
return nums
}
```
=== "Swift"
```swift title="binary_tree_bfs.swift"
[class]{}-[func]{levelOrder}
/* Level-order traversal */
func levelOrder(root: TreeNode) -> [Int] {
// Initialize queue, add root node
var queue: [TreeNode] = [root]
// Initialize a list to save the traversal sequence
var list: [Int] = []
while !queue.isEmpty {
let node = queue.removeFirst() // Dequeue
list.append(node.val) // Save node value
if let left = node.left {
queue.append(left) // Left child node enqueue
}
if let right = node.right {
queue.append(right) // Right child node enqueue
}
}
return list
}
```
=== "JS"
```javascript title="binary_tree_bfs.js"
[class]{}-[func]{levelOrder}
/* Level-order traversal */
function levelOrder(root) {
// Initialize queue, add root node
const queue = [root];
// Initialize a list to save the traversal sequence
const list = [];
while (queue.length) {
let node = queue.shift(); // Dequeue
list.push(node.val); // Save node value
if (node.left) queue.push(node.left); // Left child node enqueue
if (node.right) queue.push(node.right); // Right child node enqueue
}
return list;
}
```
=== "TS"
```typescript title="binary_tree_bfs.ts"
[class]{}-[func]{levelOrder}
/* Level-order traversal */
function levelOrder(root: TreeNode | null): number[] {
// Initialize queue, add root node
const queue = [root];
// Initialize a list to save the traversal sequence
const list: number[] = [];
while (queue.length) {
let node = queue.shift() as TreeNode; // Dequeue
list.push(node.val); // Save node value
if (node.left) {
queue.push(node.left); // Left child node enqueue
}
if (node.right) {
queue.push(node.right); // Right child node enqueue
}
}
return list;
}
```
=== "Dart"
```dart title="binary_tree_bfs.dart"
[class]{}-[func]{levelOrder}
/* Level-order traversal */
List<int> levelOrder(TreeNode? root) {
// Initialize queue, add root node
Queue<TreeNode?> queue = Queue();
queue.add(root);
// Initialize a list to save the traversal sequence
List<int> res = [];
while (queue.isNotEmpty) {
TreeNode? node = queue.removeFirst(); // Dequeue
res.add(node!.val); // Save node value
if (node.left != null) queue.add(node.left); // Left child node enqueue
if (node.right != null) queue.add(node.right); // Right child node enqueue
}
return res;
}
```
=== "Rust"
```rust title="binary_tree_bfs.rs"
[class]{}-[func]{level_order}
/* Level-order traversal */
fn level_order(root: &Rc<RefCell<TreeNode>>) -> Vec<i32> {
// Initialize queue, add root node
let mut que = VecDeque::new();
que.push_back(root.clone());
// Initialize a list to save the traversal sequence
let mut vec = Vec::new();
while let Some(node) = que.pop_front() {
// Dequeue
vec.push(node.borrow().val); // Save node value
if let Some(left) = node.borrow().left.as_ref() {
que.push_back(left.clone()); // Left child node enqueue
}
if let Some(right) = node.borrow().right.as_ref() {
que.push_back(right.clone()); // Right child node enqueue
};
}
vec
}
```
=== "C"
```c title="binary_tree_bfs.c"
[class]{}-[func]{levelOrder}
/* Level-order traversal */
int *levelOrder(TreeNode *root, int *size) {
/* Auxiliary queue */
int front, rear;
int index, *arr;
TreeNode *node;
TreeNode **queue;
/* Auxiliary queue */
queue = (TreeNode **)malloc(sizeof(TreeNode *) * MAX_SIZE);
// Queue pointer
front = 0, rear = 0;
// Add root node
queue[rear++] = root;
// Initialize a list to save the traversal sequence
/* Auxiliary array */
arr = (int *)malloc(sizeof(int) * MAX_SIZE);
// Array pointer
index = 0;
while (front < rear) {
// Dequeue
node = queue[front++];
// Save node value
arr[index++] = node->val;
if (node->left != NULL) {
// Left child node enqueue
queue[rear++] = node->left;
}
if (node->right != NULL) {
// Right child node enqueue
queue[rear++] = node->right;
}
}
// Update array length value
*size = index;
arr = realloc(arr, sizeof(int) * (*size));
// Free auxiliary array space
free(queue);
return arr;
}
```
=== "Kotlin"
```kotlin title="binary_tree_bfs.kt"
[class]{}-[func]{levelOrder}
/* Level-order traversal */
fun levelOrder(root: TreeNode?): MutableList<Int> {
// Initialize queue, add root node
val queue = LinkedList<TreeNode?>()
queue.add(root)
// Initialize a list to save the traversal sequence
val list = mutableListOf<Int>()
while (queue.isNotEmpty()) {
val node = queue.poll() // Dequeue
list.add(node?._val!!) // Save node value
if (node.left != null)
queue.offer(node.left) // Left child node enqueue
if (node.right != null)
queue.offer(node.right) // Right child node enqueue
}
return list
}
```
=== "Ruby"
```ruby title="binary_tree_bfs.rb"
[class]{}-[func]{level_order}
### Level-order traversal ###
def level_order(root)
# Initialize queue, add root node
queue = [root]
# Initialize a list to save the traversal sequence
res = []
while !queue.empty?
node = queue.shift # Dequeue
res << node.val # Save node value
queue << node.left unless node.left.nil? # Left child node enqueue
queue << node.right unless node.right.nil? # Right child node enqueue
end
res
end
```
=== "Zig"
### 2. &nbsp; Complexity Analysis
```zig title="binary_tree_bfs.zig"
[class]{}-[func]{levelOrder}
```
- **Time complexity is $O(n)$**: All nodes are visited once, using $O(n)$ time, where $n$ is the number of nodes.
- **Space complexity is $O(n)$**: In the worst case, i.e., a full binary tree, before traversing to the bottom level, the queue contains at most $(n + 1) / 2$ nodes simultaneously, occupying $O(n)$ space.
### 2. &nbsp; Complexity analysis
## 7.2.2 &nbsp; Preorder, Inorder, and Postorder Traversal
- **Time complexity is $O(n)$**: All nodes are visited once, taking $O(n)$ time, where $n$ is the number of nodes.
- **Space complexity is $O(n)$**: In the worst case, i.e., a full binary tree, before traversing to the bottom level, the queue can contain at most $(n + 1) / 2$ nodes simultaneously, occupying $O(n)$ space.
Correspondingly, preorder, inorder, and postorder traversals all belong to <u>depth-first traversal</u>, also known as <u>depth-first search (DFS)</u>, which embodies a "first go to the end, then backtrack and continue" traversal method.
## 7.2.2 &nbsp; Preorder, in-order, and post-order traversal
Figure 7-10 shows how depth-first traversal works on a binary tree. **Depth-first traversal is like "walking" around the perimeter of the entire binary tree**, encountering three positions at each node, corresponding to preorder, inorder, and postorder traversal.
Correspondingly, pre-order, in-order, and post-order traversal all belong to <u>depth-first traversal</u>, also known as <u>depth-first search (DFS)</u>, which embodies a "proceed to the end first, then backtrack and continue" traversal method.
![Preorder, inorder, and postorder traversal of a binary tree](binary_tree_traversal.assets/binary_tree_dfs.png){ class="animation-figure" }
Figure 7-10 shows the working principle of performing a depth-first traversal on a binary tree. **Depth-first traversal is like "walking" around the entire binary tree**, encountering three positions at each node, corresponding to pre-order, in-order, and post-order traversal.
<p align="center"> Figure 7-10 &nbsp; Preorder, inorder, and postorder traversal of a binary tree </p>
![Preorder, in-order, and post-order traversal of a binary search tree](binary_tree_traversal.assets/binary_tree_dfs.png){ class="animation-figure" }
<p align="center"> Figure 7-10 &nbsp; Preorder, in-order, and post-order traversal of a binary search tree </p>
### 1. &nbsp; Code implementation
### 1. &nbsp; Code Implementation
Depth-first search is usually implemented based on recursion:
@@ -176,7 +357,7 @@ Depth-first search is usually implemented based on recursion:
```python title="binary_tree_dfs.py"
def pre_order(root: TreeNode | None):
"""Pre-order traversal"""
"""Preorder traversal"""
if root is None:
return
# Visit priority: root node -> left subtree -> right subtree
@@ -185,7 +366,7 @@ Depth-first search is usually implemented based on recursion:
pre_order(root=root.right)
def in_order(root: TreeNode | None):
"""In-order traversal"""
"""Inorder traversal"""
if root is None:
return
# Visit priority: left subtree -> root node -> right subtree
@@ -194,7 +375,7 @@ Depth-first search is usually implemented based on recursion:
in_order(root=root.right)
def post_order(root: TreeNode | None):
"""Post-order traversal"""
"""Postorder traversal"""
if root is None:
return
# Visit priority: left subtree -> right subtree -> root node
@@ -206,7 +387,7 @@ Depth-first search is usually implemented based on recursion:
=== "C++"
```cpp title="binary_tree_dfs.cpp"
/* Pre-order traversal */
/* Preorder traversal */
void preOrder(TreeNode *root) {
if (root == nullptr)
return;
@@ -216,7 +397,7 @@ Depth-first search is usually implemented based on recursion:
preOrder(root->right);
}
/* In-order traversal */
/* Inorder traversal */
void inOrder(TreeNode *root) {
if (root == nullptr)
return;
@@ -226,7 +407,7 @@ Depth-first search is usually implemented based on recursion:
inOrder(root->right);
}
/* Post-order traversal */
/* Postorder traversal */
void postOrder(TreeNode *root) {
if (root == nullptr)
return;
@@ -240,7 +421,7 @@ Depth-first search is usually implemented based on recursion:
=== "Java"
```java title="binary_tree_dfs.java"
/* Pre-order traversal */
/* Preorder traversal */
void preOrder(TreeNode root) {
if (root == null)
return;
@@ -250,7 +431,7 @@ Depth-first search is usually implemented based on recursion:
preOrder(root.right);
}
/* In-order traversal */
/* Inorder traversal */
void inOrder(TreeNode root) {
if (root == null)
return;
@@ -260,7 +441,7 @@ Depth-first search is usually implemented based on recursion:
inOrder(root.right);
}
/* Post-order traversal */
/* Postorder traversal */
void postOrder(TreeNode root) {
if (root == null)
return;
@@ -274,124 +455,376 @@ Depth-first search is usually implemented based on recursion:
=== "C#"
```csharp title="binary_tree_dfs.cs"
[class]{binary_tree_dfs}-[func]{PreOrder}
/* Preorder traversal */
void PreOrder(TreeNode? root) {
if (root == null) return;
// Visit priority: root node -> left subtree -> right subtree
list.Add(root.val!.Value);
PreOrder(root.left);
PreOrder(root.right);
}
[class]{binary_tree_dfs}-[func]{InOrder}
/* Inorder traversal */
void InOrder(TreeNode? root) {
if (root == null) return;
// Visit priority: left subtree -> root node -> right subtree
InOrder(root.left);
list.Add(root.val!.Value);
InOrder(root.right);
}
[class]{binary_tree_dfs}-[func]{PostOrder}
/* Postorder traversal */
void PostOrder(TreeNode? root) {
if (root == null) return;
// Visit priority: left subtree -> right subtree -> root node
PostOrder(root.left);
PostOrder(root.right);
list.Add(root.val!.Value);
}
```
=== "Go"
```go title="binary_tree_dfs.go"
[class]{}-[func]{preOrder}
/* Preorder traversal */
func preOrder(node *TreeNode) {
if node == nil {
return
}
// Visit priority: root node -> left subtree -> right subtree
nums = append(nums, node.Val)
preOrder(node.Left)
preOrder(node.Right)
}
[class]{}-[func]{inOrder}
/* Inorder traversal */
func inOrder(node *TreeNode) {
if node == nil {
return
}
// Visit priority: left subtree -> root node -> right subtree
inOrder(node.Left)
nums = append(nums, node.Val)
inOrder(node.Right)
}
[class]{}-[func]{postOrder}
/* Postorder traversal */
func postOrder(node *TreeNode) {
if node == nil {
return
}
// Visit priority: left subtree -> right subtree -> root node
postOrder(node.Left)
postOrder(node.Right)
nums = append(nums, node.Val)
}
```
=== "Swift"
```swift title="binary_tree_dfs.swift"
[class]{}-[func]{preOrder}
/* Preorder traversal */
func preOrder(root: TreeNode?) {
guard let root = root else {
return
}
// Visit priority: root node -> left subtree -> right subtree
list.append(root.val)
preOrder(root: root.left)
preOrder(root: root.right)
}
[class]{}-[func]{inOrder}
/* Inorder traversal */
func inOrder(root: TreeNode?) {
guard let root = root else {
return
}
// Visit priority: left subtree -> root node -> right subtree
inOrder(root: root.left)
list.append(root.val)
inOrder(root: root.right)
}
[class]{}-[func]{postOrder}
/* Postorder traversal */
func postOrder(root: TreeNode?) {
guard let root = root else {
return
}
// Visit priority: left subtree -> right subtree -> root node
postOrder(root: root.left)
postOrder(root: root.right)
list.append(root.val)
}
```
=== "JS"
```javascript title="binary_tree_dfs.js"
[class]{}-[func]{preOrder}
/* Preorder traversal */
function preOrder(root) {
if (root === null) return;
// Visit priority: root node -> left subtree -> right subtree
list.push(root.val);
preOrder(root.left);
preOrder(root.right);
}
[class]{}-[func]{inOrder}
/* Inorder traversal */
function inOrder(root) {
if (root === null) return;
// Visit priority: left subtree -> root node -> right subtree
inOrder(root.left);
list.push(root.val);
inOrder(root.right);
}
[class]{}-[func]{postOrder}
/* Postorder traversal */
function postOrder(root) {
if (root === null) return;
// Visit priority: left subtree -> right subtree -> root node
postOrder(root.left);
postOrder(root.right);
list.push(root.val);
}
```
=== "TS"
```typescript title="binary_tree_dfs.ts"
[class]{}-[func]{preOrder}
/* Preorder traversal */
function preOrder(root: TreeNode | null): void {
if (root === null) {
return;
}
// Visit priority: root node -> left subtree -> right subtree
list.push(root.val);
preOrder(root.left);
preOrder(root.right);
}
[class]{}-[func]{inOrder}
/* Inorder traversal */
function inOrder(root: TreeNode | null): void {
if (root === null) {
return;
}
// Visit priority: left subtree -> root node -> right subtree
inOrder(root.left);
list.push(root.val);
inOrder(root.right);
}
[class]{}-[func]{postOrder}
/* Postorder traversal */
function postOrder(root: TreeNode | null): void {
if (root === null) {
return;
}
// Visit priority: left subtree -> right subtree -> root node
postOrder(root.left);
postOrder(root.right);
list.push(root.val);
}
```
=== "Dart"
```dart title="binary_tree_dfs.dart"
[class]{}-[func]{preOrder}
/* Preorder traversal */
void preOrder(TreeNode? node) {
if (node == null) return;
// Visit priority: root node -> left subtree -> right subtree
list.add(node.val);
preOrder(node.left);
preOrder(node.right);
}
[class]{}-[func]{inOrder}
/* Inorder traversal */
void inOrder(TreeNode? node) {
if (node == null) return;
// Visit priority: left subtree -> root node -> right subtree
inOrder(node.left);
list.add(node.val);
inOrder(node.right);
}
[class]{}-[func]{postOrder}
/* Postorder traversal */
void postOrder(TreeNode? node) {
if (node == null) return;
// Visit priority: left subtree -> right subtree -> root node
postOrder(node.left);
postOrder(node.right);
list.add(node.val);
}
```
=== "Rust"
```rust title="binary_tree_dfs.rs"
[class]{}-[func]{pre_order}
/* Preorder traversal */
fn pre_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
[class]{}-[func]{in_order}
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
// Visit priority: root node -> left subtree -> right subtree
let node = node.borrow();
res.push(node.val);
dfs(node.left.as_ref(), res);
dfs(node.right.as_ref(), res);
}
}
dfs(root, &mut result);
[class]{}-[func]{post_order}
result
}
/* Inorder traversal */
fn in_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
// Visit priority: left subtree -> root node -> right subtree
let node = node.borrow();
dfs(node.left.as_ref(), res);
res.push(node.val);
dfs(node.right.as_ref(), res);
}
}
dfs(root, &mut result);
result
}
/* Postorder traversal */
fn post_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
// Visit priority: left subtree -> right subtree -> root node
let node = node.borrow();
dfs(node.left.as_ref(), res);
dfs(node.right.as_ref(), res);
res.push(node.val);
}
}
dfs(root, &mut result);
result
}
```
=== "C"
```c title="binary_tree_dfs.c"
[class]{}-[func]{preOrder}
/* Preorder traversal */
void preOrder(TreeNode *root, int *size) {
if (root == NULL)
return;
// Visit priority: root node -> left subtree -> right subtree
arr[(*size)++] = root->val;
preOrder(root->left, size);
preOrder(root->right, size);
}
[class]{}-[func]{inOrder}
/* Inorder traversal */
void inOrder(TreeNode *root, int *size) {
if (root == NULL)
return;
// Visit priority: left subtree -> root node -> right subtree
inOrder(root->left, size);
arr[(*size)++] = root->val;
inOrder(root->right, size);
}
[class]{}-[func]{postOrder}
/* Postorder traversal */
void postOrder(TreeNode *root, int *size) {
if (root == NULL)
return;
// Visit priority: left subtree -> right subtree -> root node
postOrder(root->left, size);
postOrder(root->right, size);
arr[(*size)++] = root->val;
}
```
=== "Kotlin"
```kotlin title="binary_tree_dfs.kt"
[class]{}-[func]{preOrder}
/* Preorder traversal */
fun preOrder(root: TreeNode?) {
if (root == null) return
// Visit priority: root node -> left subtree -> right subtree
list.add(root._val)
preOrder(root.left)
preOrder(root.right)
}
[class]{}-[func]{inOrder}
/* Inorder traversal */
fun inOrder(root: TreeNode?) {
if (root == null) return
// Visit priority: left subtree -> root node -> right subtree
inOrder(root.left)
list.add(root._val)
inOrder(root.right)
}
[class]{}-[func]{postOrder}
/* Postorder traversal */
fun postOrder(root: TreeNode?) {
if (root == null) return
// Visit priority: left subtree -> right subtree -> root node
postOrder(root.left)
postOrder(root.right)
list.add(root._val)
}
```
=== "Ruby"
```ruby title="binary_tree_dfs.rb"
[class]{}-[func]{pre_order}
### Pre-order traversal ###
def pre_order(root)
return if root.nil?
[class]{}-[func]{in_order}
# Visit priority: root node -> left subtree -> right subtree
$res << root.val
pre_order(root.left)
pre_order(root.right)
end
[class]{}-[func]{post_order}
```
### In-order traversal ###
def in_order(root)
return if root.nil?
=== "Zig"
# Visit priority: left subtree -> root node -> right subtree
in_order(root.left)
$res << root.val
in_order(root.right)
end
```zig title="binary_tree_dfs.zig"
[class]{}-[func]{preOrder}
### Post-order traversal ###
def post_order(root)
return if root.nil?
[class]{}-[func]{inOrder}
[class]{}-[func]{postOrder}
# Visit priority: left subtree -> right subtree -> root node
post_order(root.left)
post_order(root.right)
$res << root.val
end
```
!!! tip
Depth-first search can also be implemented based on iteration, interested readers can study this on their own.
Figure 7-11 shows the recursive process of pre-order traversal of a binary tree, which can be divided into two opposite parts: "recursion" and "return".
Figure 7-11 shows the recursive process of preorder traversal of a binary tree, which can be divided into two opposite parts: "recursion" and "return".
1. "Recursion" means starting a new method, the program accesses the next node in this process.
2. "Return" means the function returns, indicating the current node has been fully accessed.
1. "Recursion" means opening a new method, where the program accesses the next node in this process.
2. "Return" means the function returns, indicating that the current node has been fully visited.
=== "<1>"
![The recursive process of pre-order traversal](binary_tree_traversal.assets/preorder_step1.png){ class="animation-figure" }
![The recursive process of preorder traversal](binary_tree_traversal.assets/preorder_step1.png){ class="animation-figure" }
=== "<2>"
![preorder_step2](binary_tree_traversal.assets/preorder_step2.png){ class="animation-figure" }
@@ -423,9 +856,9 @@ Figure 7-11 shows the recursive process of pre-order traversal of a binary tree,
=== "<11>"
![preorder_step11](binary_tree_traversal.assets/preorder_step11.png){ class="animation-figure" }
<p align="center"> Figure 7-11 &nbsp; The recursive process of pre-order traversal </p>
<p align="center"> Figure 7-11 &nbsp; The recursive process of preorder traversal </p>
### 2. &nbsp; Complexity analysis
### 2. &nbsp; Complexity Analysis
- **Time complexity is $O(n)$**: All nodes are visited once, using $O(n)$ time.
- **Space complexity is $O(n)$**: In the worst case, i.e., the tree degenerates into a linked list, the recursion depth reaches $n$, the system occupies $O(n)$ stack frame space.
- **Space complexity is $O(n)$**: In the worst case, i.e., the tree degenerates into a linked list, the recursion depth reaches $n$, and the system occupies $O(n)$ stack frame space.
+8 -8
View File
@@ -9,14 +9,14 @@ icon: material/graph-outline
!!! abstract
The towering tree exudes a vibrant essence, boasting profound roots and abundant foliage, yet its branches are sparsely scattered, creating an ethereal aura.
It shows us the vivid form of divide-and-conquer in data.
Towering trees are full of vitality, with deep roots and lush leaves, spreading branches and flourishing.
They show us the vivid form of divide and conquer in data.
## Chapter contents
- [7.1 &nbsp; Binary tree](binary_tree.md)
- [7.2 &nbsp; Binary tree traversal](binary_tree_traversal.md)
- [7.3 &nbsp; Array Representation of tree](array_representation_of_tree.md)
- [7.4 &nbsp; Binary Search tree](binary_search_tree.md)
- [7.5 &nbsp; AVL tree *](avl_tree.md)
- [7.1 &nbsp; Binary Tree](binary_tree.md)
- [7.2 &nbsp; Binary Tree Traversal](binary_tree_traversal.md)
- [7.3 &nbsp; Array Representation of Tree](array_representation_of_tree.md)
- [7.4 &nbsp; Binary Search Tree](binary_search_tree.md)
- [7.5 &nbsp; AVL Tree *](avl_tree.md)
- [7.6 &nbsp; Summary](summary.md)
+19 -19
View File
@@ -4,19 +4,19 @@ comments: true
# 7.6 &nbsp; Summary
### 1. &nbsp; Key review
### 1. &nbsp; Key Review
- A binary tree is a non-linear data structure that reflects the "divide and conquer" logic of splitting one into two. Each binary tree node contains a value and two pointers, which point to its left and right child nodes, respectively.
- For a node in a binary tree, its left (right) child node and the tree formed below it are collectively called the node's left (right) subtree.
- Terms related to binary trees include root node, leaf node, level, degree, edge, height, and depth.
- The operations of initializing a binary tree, inserting nodes, and removing nodes are similar to those of linked list operations.
- Common types of binary trees include perfect binary trees, complete binary trees, full binary trees, and balanced binary trees. The perfect binary tree represents the ideal state, while the linked list is the worst state after degradation.
- A binary tree can be represented using an array by arranging the node values and empty slots in a level-order traversal sequence and implementing pointers based on the index mapping relationship between parent nodes and child nodes.
- The level-order traversal of a binary tree is a breadth-first search method, which reflects a layer-by-layer traversal manner of "expanding circle by circle." It is usually implemented using a queue.
- Pre-order, in-order, and post-order traversals are all depth-first search methods, reflecting the traversal manner of "going to the end first, then backtracking to continue." They are usually implemented using recursion.
- A binary search tree is an efficient data structure for element searching, with the time complexity of search, insert, and remove operations all being $O(\log n)$. When a binary search tree degrades into a linked list, these time complexities deteriorate to $O(n)$.
- An AVL tree, also known as a balanced binary search tree, ensures that the tree remains balanced after continuous node insertions and removals through rotation operations.
- Rotation operations in an AVL tree include right rotation, left rotation, right-left rotation, and left-right rotation. After node insertion or removal, the AVL tree rebalances itself by performing these rotations in a bottom-up manner.
- A binary tree is a non-linear data structure that embodies the divide-and-conquer logic of "one divides into two". Each binary tree node contains a value and two pointers, which respectively point to its left and right child nodes.
- For a certain node in a binary tree, the tree formed by its left (right) child node and all nodes below is called the left (right) subtree of that node.
- Related terminology of binary trees includes root node, leaf node, level, degree, edge, height, and depth.
- The initialization, node insertion, and node removal operations of binary trees are similar to those of linked lists.
- Common types of binary trees include perfect binary trees, complete binary trees, full binary trees, and balanced binary trees. The perfect binary tree is the ideal state, while the linked list is the worst state after degradation.
- A binary tree can be represented using an array by arranging node values and empty slots in level-order traversal sequence, and implementing pointers based on the index mapping relationship between parent and child nodes.
- Level-order traversal of a binary tree is a breadth-first search method, embodying a layer-by-layer traversal approach of "expanding outward circle by circle", typically implemented using a queue.
- Preorder, inorder, and postorder traversals all belong to depth-first search, embodying a traversal approach of "first go to the end, then backtrack and continue", typically implemented using recursion.
- A binary search tree is an efficient data structure for element searching, with search, insertion, and removal operations all having time complexity of $O(\log n)$. When a binary search tree degenerates into a linked list, all time complexities degrade to $O(n)$.
- An AVL tree, also known as a balanced binary search tree, ensures the tree remains balanced after continuous node insertions and removals through rotation operations.
- Rotation operations in AVL trees include right rotation, left rotation, left rotation then right rotation, and right rotation then left rotation. After inserting or removing nodes, AVL trees perform rotation operations from bottom to top to restore the tree to balance.
### 2. &nbsp; Q & A
@@ -28,21 +28,21 @@ Yes, because height and depth are typically defined as "the number of edges pass
Taking the binary search tree as an example, the operation of removing a node needs to be handled in three different scenarios, each requiring multiple steps of node operations.
**Q**: Why are there three sequences: pre-order, in-order, and post-order for DFS traversal of a binary tree, and what are their uses?
**Q**: Why does DFS traversal of binary trees have three orders: preorder, inorder, and postorder, and what are their uses?
Similar to sequential and reverse traversal of arrays, pre-order, in-order, and post-order traversals are three methods of traversing a binary tree, allowing us to obtain a traversal result in a specific order. For example, in a binary search tree, since the node sizes satisfy `left child node value < root node value < right child node value`, we can obtain an ordered node sequence by traversing the tree in the "left $\rightarrow$ root $\rightarrow$ right" priority.
Similar to forward and reverse traversal of arrays, preorder, inorder, and postorder traversals are three methods of binary tree traversal that allow us to obtain a traversal result in a specific order. For example, in a binary search tree, since nodes satisfy the relationship `left child node value < root node value < right child node value`, we only need to traverse the tree with the priority of "left $\rightarrow$ root $\rightarrow$ right" to obtain an ordered node sequence.
**Q**: In a right rotation operation that deals with the relationship between the imbalance nodes `node`, `child`, `grand_child`, isn't the connection between `node` and its parent node and the original link of `node` lost after the right rotation?
**Q**: In a right rotation operation handling the relationship between unbalanced nodes `node`, `child`, and `grand_child`, doesn't the connection between `node` and its parent node get lost after the right rotation?
We need to view this problem from a recursive perspective. The `right_rotate(root)` operation passes the root node of the subtree and eventually returns the root node of the rotated subtree with `return child`. The connection between the subtree's root node and its parent node is established after this function returns, which is outside the scope of the right rotation operation's maintenance.
We need to view this problem from a recursive perspective. The right rotation operation `right_rotate(root)` passes in the root node of the subtree and eventually returns the root node of the subtree after rotation with `return child`. The connection between the subtree's root node and its parent node is completed after the function returns, which is not within the maintenance scope of the right rotation operation.
**Q**: In C++, functions are divided into `private` and `public` sections. What considerations are there for this? Why are the `height()` function and the `updateHeight()` function placed in `public` and `private`, respectively?
It depends on the scope of the method's use. If a method is only used within the class, then it is designed to be `private`. For example, it makes no sense for users to call `updateHeight()` on their own, as it is just a step in the insertion or removal operations. However, `height()` is for accessing node height, similar to `vector.size()`, thus it is set to `public` for use.
It mainly depends on the method's usage scope. If a method is only used within the class, then it is designed as `private`. For example, calling `updateHeight()` alone by the user makes no sense, as it is only a step in insertion or removal operations. However, `height()` is used to access node height, similar to `vector.size()`, so it is set to `public` for ease of use.
**Q**: How do you build a binary search tree from a set of input data? Is the choice of root node very important?
Yes, the method for building the tree is provided in the `build_tree()` method in the binary search tree code. As for the choice of the root node, we usually sort the input data and then select the middle element as the root node, recursively building the left and right subtrees. This approach maximizes the balance of the tree.
Yes, the method for building a tree is provided in the `build_tree()` method in the binary search tree code. As for the choice of root node, we typically sort the input data, then select the middle element as the root node, and recursively build the left and right subtrees. This approach maximizes the tree's balance.
**Q**: In Java, do you always have to use the `equals()` method for string comparison?
@@ -51,7 +51,7 @@ In Java, for primitive data types, `==` is used to compare whether the values of
- `==`: Used to compare whether two variables point to the same object, i.e., whether their positions in memory are the same.
- `equals()`: Used to compare whether the values of two objects are equal.
Therefore, to compare values, we should use `equals()`. However, strings initialized with `String a = "hi"; String b = "hi";` are stored in the string constant pool and point to the same object, so `a == b` can also be used to compare the contents of two strings.
Therefore, if we want to compare values, we should use `equals()`. However, strings initialized via `String a = "hi"; String b = "hi";` are stored in the string constant pool and point to the same object, so `a == b` can also be used to compare the contents of the two strings.
**Q**: Before reaching the bottom level, is the number of nodes in the queue $2^h$ in breadth-first traversal?