二叉树
前序遍历(伪代码)
根->左->右
递归
void pre_order(Node root) {
// 处理根节点
process(root);
// 遍历左子树
pre_order(root.left);
// 遍历右子树
pre_order(root.right);
}
非递归
void pre_order_iter(Node root) {
// 根节点入栈
stack.push(root);
while !stack.is_empty() {
// 弹出栈顶节点
let node = stack.pop();
// 处理节点 process(node);
if node.right != null {
// 将右孩子入栈
stack.push(node.right);
}
if node.left != null {
// 左孩子入栈
stack.push(node.left);
}
}
}
中序遍历(伪代码)
左->根->右
递归
void in_order(Node root) {
// 遍历左子树
in_order(root.left);
// 处理根节点
process(root);
// 遍历右子树
in_order(root.right);
}
非递归
void push_left_childs(Stack stack, Node root) {
while root != NULL {
stack.push(root);
root = root.left;
}
}
void in_order_iter(Node root) {
Stack stack;
push_left_childs(stack, root);
while !stack.is_empty() {
// 弹出栈顶节点
let node = stack.pop();
// 处理节点
process(node);
// 处理右子树
if node.right != NULL{
push_left_childs(stack, node.right);
}
}
}
后序遍历(伪代码)
左->右->根
递归
void post_order(Node root) {
// 遍历左子树
post_order(root.left);
// 遍历右子树
post_order(root.right);
// 处理根节点
process(root);
}
非递归
void post_order_iter(Node root) {
Stack stack;
stack.push(root);
// 记录上一个处理节点,来判断节点的子节点是否已处理
Node pre = NULL;
while !stack.is_empty() {
// 获取栈顶节点
let node = stack.top();
if node.left == NULL && node.right == NULL || node.left == pre || node .right == pre {
// 处理节点
process(node);
stack.pop();
pre = node;
} else {
if node.right != NULL {
stack.push(node.right);
}
if node.left != NULL {
stack.push(node.left);
}
}
}
}
层次遍历(BFS)
void level_order_v1(Node root) {
Queue queue;
queue.push_back(root);
while !queue.is_empty() {
let node = queue.pop_front();
// 处理节点
process(node);
if node.left != NULL {
queue.push_back(node.left);
}
if node.right != NULL {
queue.push_back(node.right);
}
}
}
void level_order_v2(Node root) {
Queue queue;
queue.push_back(root);
while !queue.is_empty() {
let n = queue.len();
// 可以统计每层数据
for i = 0; i < n; i++ {
let node = queue.pop_front();
// 处理节点
process(node);
if node.left != NULL {
queue.push_back(node.left);
}
if node.right != NULL {
queue.push_back(node.right);
}
}
}
}