关于二叉树的学习,最多的也就是二叉树的各种遍历,求结点,求深度,根据遍历方式创建,这几天学习了各种操作和oj上面的题,知识点没学太多,主要还是理解二叉树的遍历顺序。
下面是关于二叉树的各种操作:
import java.util.*;
/**
* Created with IntelliJ IDEA.
* Description:
* User: 联想
* Date: 2020-11-05
* Time: 10:42
*/
class Node {
char val;
Node left;
Node right;
public Node(char val) {
this.val = val;
}
public Node(char val, Node left, Node right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public 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;
}
//前序遍历
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.println(root.val + " ");
}
static int size = 0;
// 遍历思路-求结点个数
int getSize1(Node root) {
if (root == null) return 0;
size++;
getSize1(root.left);
getSize1(root.right);
return size;
}
//子问题思路求节点个数
int getSize2(Node root) {
if (root == null) return 0;
return getSize2(root.left) + getSize2(root.right) + 1;
}
// 遍历思路-求叶子结点个数
static int leafSize = 0;
int getLeafSize1(Node root) {
if (root == null) return 0;
if (root.left == null && root.right == null) {
leafSize++;
}
getLeafSize1(root.left);
getLeafSize1(root.right);
return leafSize;
}
// 子问题思路-求叶子结点个数
int getLeafSize2(Node root) {
if (root == null) return 0;