创建一颗二叉树,按照三种遍历方式,分别输出遍历的结果。
二叉树
首先,二叉树是一种「数据结构」,详细的介绍可以通过 「探索」卡片 来进行学习。简单来说,就是一个包含节点,以及它的左右孩子的一种数据结构。
遍历方式:
如果对每一个节点进行编号,你会用什么方式去遍历每个节点呢?
如果你按照 根节点 -> 左孩子 -> 右孩子 的方式遍历,即「先序遍历」,每次先遍历根节点,遍历结果为 1 2 4 5 3 6 7;
同理,如果你按照 左孩子 -> 根节点 -> 右孩子 的方式遍历,即「中序序遍历」,遍历结果为 4 2 5 1 6 3 7;
如果你按照 左孩子 -> 右孩子 -> 根节点 的方式遍历,即「后序序遍历」,遍历结果为 4 5 2 6 7 3 1;
最后,层次遍历就是按照每一层从左向右的方式进行遍历,遍历结果为 1 2 3 4 5 6 7。
package com.bite.BinaryTree;
/**
* @program: bite
* @description
* @author: wenwen
* @create: 2021-07-16 14:28
**/
//==========================使用前序遍历===========================
class Node{
public char val;
public Node left;
public Node right;
public Node(char val){
this.val = val;
}
}
class BinaryTree {
public Node createTree(){
Node A = new Node('A');
Node B = new Node('B');
Node C = new Node('C');
Node D = new Node('D');
Node E = new Node('E');
Node F = new Node('F');
Node G = new Node('G');
Node H = new Node('H');
A.left = B;
A.right = C;
B.left = D;
B.right = E;
E.right = H;
C.left = F;
C.right = G;
return A;
}
// 前序遍历
public void preOrderTraversal(Node root){
if(root == null){
return;
}
System.out.print(root.val+" ");
preOrderTraversal(root.left);
preOrderTraversal(root.right);
};
// 中序遍历
void inOrderTraversal(Node root){
if(root == null){
return;
}
inOrderTraversal(root.left);
System.out.print(root.val+" ");
inOrderTraversal(root.right);
};
// 后序遍历
void postOrderTraversal(Node root){
if(root == null){
return;
}
postOrderTraversal(root.left);
postOrderTraversal(root.right);
System.out.print(root.val+" ");
};
public static void main(String[] args){
BinaryTree binaryTree = new BinaryTree();
Node root = binaryTree.createTree();
// binaryTree.preOrderTraversal(root);
// binaryTree.inOrderTraversal(root);
// System.out.println("====================");
// System.out.println(binaryTree.getLeafSize2(root));
// System.out.println(binaryTree.getKLevelSize(root, 4));
// System.out.println(binaryTree.getHeight(root));
//
// System.out.println(binaryTree.find(root, 'E').val);
//=============================================
binaryTree.getSize1(root);
System.out.println(BinaryTree.size);
System.out.println(binaryTree.getSize2(root));
System.out.println(binaryTree.getLeafSize2(root));
binaryTree.getLeafsize1(root);
System.out.println(BinaryTree.leafsize);
Node ret = binaryTree.find(root, 'E');
if(ret == null){
System.out.println("没有这个节点啊");
} else{
System.out.println(ret.val);
}
}
}