Binary tree depth-first traversal
Yesterday I brushed the three traversal problems of binary trees on leetcode. Summarize the respective non- recursive (iterative) algorithms.
- traversal of binary tree
- Breadth- first traversal
- depth- first traversal
- Preorder traversal => root - left - right
- Inorder traversal => left - root - right
- Post -order traversal => left-right-root
preorder traversal
Application: Printing a structured document
The idea is as follows
code
var preorderTraversal = function(root) {
const stack = []
const res = []
if (root) {stack.push(root)}
while (stack.length) {
const n = stack.pop()
res.push(n.val)
if(n.right) stack.push(n.right)
if(n.left) stack.push(n.left)
}
return res
};
复制代码
Inorder traversal
Application: Queue operations on logarithms
The idea is as follows
code
var inorderTraversal = function(root) {
const stack = []
const res = []
let p = root
while (stack.length || p) {
while (p) {
stack.push(p)
p = p.left
}
const n = stack.pop()
res.push(n.val)
p = n.right
}
return res
};
复制代码
post-order traversal
Application: Calculate the space occupied by all files in a directory and its subdirectories
The idea is as follows
code
var postorderTraversal = function(root) {
const res = []
const stack = []
const outputStack = []
if (root) stack.push(root)
while (stack.length) {
const n = stack.pop()
outputStack.push(n)
n.left && stack.push(n.left)
n.right && stack.push(n.right)
}
while (outputStack.length) {
const n = outputStack.pop()
res.push(n.val)
}
return res
};
复制代码