二叉树的四种遍历
1.前序遍历;
先访问根结点,然后再访问左子树,最后访问右子树。
2.中序遍历
先访问左子树,中间访问根节点,最后访问右子树。
3.后序遍历;
先访问左子树,再访问右子树,最后访问根节点。
4.从左到右,从上到下一层一层的访问二叉树。
1、前序遍历
/*
* 路人假helloWorld
*/
//前序遍历
//获取整个树中所有的键
public Queue<Key> preErgodic(){
Queue<Key> keys = new Queue<>();
preErgodic(root,keys);
return keys;
}
//获取指定树x的所有键,并放入到keys队列中
private void preErgodic(Node x,Queue<Key> keys){
//如果当前结点为空,则返回
if (x == null){
return;
}
//将当前结点的key值放入队列中
keys.enqueue(x.key);
System.out.println(x.key);
//如果当前结点的左子树不为空
if (x.left != null){
preErgodic(x.left,keys);
}
//如果当前结点右子树不为空
if (x.right != null){
preErgodic(x.right,keys);
}
}
2、中序遍历
//中序遍历
public Queue<Key> midErgodic(){
Queue<Key> keys = new Queue<>();
midErgodic(root,keys);
return keys;
}
private void midErgodic(Node x,Queue<Key> keys){
if (x == null){
return;
}
if (x.left != null){
midErgodic(x.left,keys);
}
keys.enqueue(x.key);
if (x.left != null){
midErgodic(x.right,keys);
}
}
3、后序遍历
//后序遍历
public Queue<Key> afterErgodic(){
Queue<Key> keys = new Queue<>();
afterErgodic(root,keys);
return keys;
}
private void afterErgodic(Node x,Queue<Key> keys){
if (x == null){
return;
}
if (x.left != null){
afterErgodic(x.left,keys);
}
if (x.left != null){
afterErgodic(x.right,keys);
}
keys.enqueue(x.key);
}
4、层序遍历
//层序遍历
public Queue<Key> layerErgodic(){
//定义一个队列存储键
Queue<Key> keys = new Queue<>();
//定义一个队列按顺序存储结点
Queue<Node> nodes = new Queue<>();
//先将根节点root存入队列中
nodes.enqueue(root);
//当存储结点的队列不为空时就循环取出结点
while(!nodes.isEmpty()){
//取出结点
Node n = nodes.dequeue();
//先将这个结点的键放入键队列中
keys.enqueue(n.key);
//判断当前取出的结点是否有左子树,如果有,则将左子树放入队列中
if (n.left != null){
nodes.enqueue(n.left);
}
//判断当前取出的结点是否有右子树,如果有,则将右子树放入队列中
if (n.right != null){
nodes.enqueue(n.right);
}
}
return keys;
}
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术