Java实现二叉树的创建与四种遍历方式(前,中,后,层)-创新互联
文章目录
本文标题:Java实现二叉树的创建与四种遍历方式(前,中,后,层)-创新互联
URL网址:http://scyanting.com/article/cdpoje.html
- 1.二叉树节点的创建
- 2.二叉树的先序遍历
- 3.二叉树的中序遍历
- 4.二叉树的后序遍历
- 5.二叉树的层序遍历
💎💎💎💎💎
更多资源链接,欢迎访问作者gitee仓库:https://gitee.com/fanggaolei/learning-notes-warehouse/tree/master
1.二叉树节点的创建哔哩哔哩算法题视频讲解:Java初级算法合集
public class TreeNode { int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) {this.val = val;}
TreeNode(int val, TreeNode left, TreeNode right) { this.val = val;
this.left = left;
this.right = right;
}
}
这里我们需要理解二叉树中会存储3个值,分别为自己本身的val值和两个指针,这两个指针分别会指向两个新的节点,或者指向为空。
先序遍历:3 2 3 4 2 4 3
中序遍历:3 2 4 3 4 2 3
后序遍历:3 4 2 4 3 2 3
层序遍历:3 2 2 3 4 4 3
public class TEST {public static void main(String[] args) {//第三层
TreeNode treeNode1=new TreeNode(3);
TreeNode treeNode2=new TreeNode(4);
TreeNode treeNode3=new TreeNode(4);
TreeNode treeNode4=new TreeNode(3);
//第二层
TreeNode treeNode5=new TreeNode(2,treeNode1,treeNode2);
TreeNode treeNode6=new TreeNode(2,treeNode3,treeNode4);
//第一层
TreeNode treeNoderoot=new TreeNode(3,treeNode5,treeNode6);
Solution solution=new Solution();
solution.isSymmetric(treeNoderoot);//中序遍历
//solution.inOrderTraveral(treeNoderoot);//中序遍历
//solution.postOrderTraveral(treeNoderoot);//后序遍历
}
}
class TreeNode { int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) {this.val = val;}
TreeNode(int val, TreeNode left, TreeNode right) { this.val = val;
this.left = left;
this.right = right;
}
}
}
2.二叉树的先序遍历//二叉树的先序遍历
class Solution{public void isSymmetric(TreeNode node){if(node == null){return;
}
System.out.print(node.val+" ");
isSymmetric(node.left);
isSymmetric(node.right);
}
3.二叉树的中序遍历//二叉树中序遍历
public static void inOrderTraveral(TreeNode node){if(node == null){return;
}
inOrderTraveral(node.left);
System.out.print(node.val+" ");
inOrderTraveral(node.right);
}
4.二叉树的后序遍历//二叉树后续遍历
public static void postOrderTraveral(TreeNode node){if(node == null){return;
}
postOrderTraveral(node.left);
postOrderTraveral(node.right);
System.out.print(node.val+" ");
}
5.二叉树的层序遍历public List>levelOrder(TreeNode root) {//边界条件判断
if (root == null)
return new ArrayList<>();
//队列
Queuequeue = new LinkedList<>();
List>res = new ArrayList<>();
//根节点入队
queue.add(root);
//如果队列不为空就继续循环
while (!queue.isEmpty()) {//BFS打印,levelNum表示的是每层的结点数
int levelNum = queue.size();
//subList存储的是每层的结点值
ListsubList = new ArrayList<>();
for (int i = 0; i< levelNum; i++) {//出队
TreeNode node = queue.poll();
subList.add(node.val);
//左右子节点如果不为空就加入到队列中
if (node.left != null)
queue.add(node.left);
if (node.right != null)
queue.add(node.right);
}
//把每层的结点值存储在res中,
res.add(subList);
}
return res;
}
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
本文标题:Java实现二叉树的创建与四种遍历方式(前,中,后,层)-创新互联
URL网址:http://scyanting.com/article/cdpoje.html