💎💎💎💎💎
更多资源链接,欢迎访问作者gitee仓库:https://gitee.com/fanggaolei/learning-notes-warehouse/tree/master
哔哩哔哩算法题视频讲解:Java初级算法合集
1.二叉树节点的创建
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<List<Integer>> levelOrder(TreeNode root) {
//边界条件判断
if (root == null)
return new ArrayList<>();
//队列
Queue<TreeNode> queue = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
//根节点入队
queue.add(root);
//如果队列不为空就继续循环
while (!queue.isEmpty()) {
//BFS打印,levelNum表示的是每层的结点数
int levelNum = queue.size();
//subList存储的是每层的结点值
List<Integer> subList = 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;
}