二叉树定义不多说了
用链表实现二叉树
首先,定义一个类
class Node{
char value;
Node left;
Node right;
public Node(char value){
this.value = value;
left = right = null;
}
}
Node 也可以叫二叉链
遍历的方法有三种:
- 前序遍历
根左右 - 中序遍历
左根右 - 后序遍历
左右根
注意左和右是指左子树和右子树
前序遍历
public void preOrder(Node root){
//终止条件: 空树
if(root == null){
return;
}
else{
//递推
//根
System.out.print(root.value);
//左子树
preOrder(root.left);
//右子树
preOrder(root.right);
}
}
中序遍历
public void inOrder(Node root){
if(root != null){
//访问左子树
inOrder(root.left);
//根
System.out.print(root.value);
//访问右子树
inOrder(root.right);
}
}
在这里插入代码片
后序遍历
public void postOrfer(Node root){
if(root != null){
//左子树
postOrfer(root.left);
//右子树
postOrfer(root.right);
//根
System.out.print(root.value);
}
}
当前树的结点个数
public void getSize1(Node root){
if(root != null){
//左子树
getSize1(root.left);
//右子树
getSize1(root.right);
//根
++size;
}
}
public int getSize2(Node root){
if(root == null)
return 0;
if(root.left == null && root.right == null)
return 1;
//整棵树节点: 当前节点 + 左右子树节点的个数
return getSize2(root.left) + getSize2(root.right) + 1;
}
思路:当前节点加左右子树的结点个数
求这颗树的叶子个数
public int getLeafSize2(Node root){
if(root == null)
return 0;
if(root.left == null && root.right == null)
return 1;
return getLeafSize2(root.left) + getLeafSize2(root.right);
}
public int getKSize(Node root, int k){
if(root == null)
return 0;
if(k == 1)
return 1;
return getKSize(root.left, k - 1) + getKSize(root.right, k - 1);
}
思路:左右树的叶子个数和