package tree;
import java.util.ArrayList;
import java.util.List;
public class VisitTree {
public static void main(String[] args) {
TreeNode[] nodes = new TreeNode[10];
//创建二叉树
for(int i=0;i<10;i++)
{
nodes[i] = new TreeNode(i);
}
for(int i=0;i<10;i++)
{
if(2*i+1<10)
{
nodes[i].left = nodes[2*i+1];
}
if(2*i+2<10)
{
nodes[i].right = nodes[2*i+2];
}
}
// preOrder(nodes[0]);
// midOrder(nodes[0]);
// afterOrder(nodes[0]);
// System.out.println("节点数为:"+count(nodes[0]));
// System.out.println("高度为"+height(nodes[0]));
// for(TreeNode n:preOrder02(nodes[0]))
// {
// System.out.println(n.value);
// }
}
//递归前序遍历二叉树
public static void preOrder(TreeNode node) {
System.out.println(node.value);
TreeNode left = node.left;
if(left!=null) {
preOrder(left);
}
TreeNode right = node.right;
if(right!=null)
{
preOrder(right);
}
}
//非递归先序遍历
static List<TreeNode> pre = new ArrayList<TreeNode>();
public static List<TreeNode> preOrder02(TreeNode node)
{
if(node!=null)
{
pre.add(node);
}
if(node.left!=null)
{
preOrder02(node.left);
}
if(node.right!=null)
{
preOrder02(node.right);
}
return pre;
}
//递归中序遍历二叉树
public static void midOrder(TreeNode node)
{
if(node.left!=null)
{
TreeNode left = node.left;
midOrder(left);
}
System.out.println(node.value);
if(node.right!=null)
{
TreeNode right = node.right;
midOrder(right);
}
}
//递归后序遍历二叉树
public static void afterOrder(TreeNode node)
{
if(node.left!=null)
{
TreeNode left = node.left;
afterOrder(left);
}
if(node.right!=null)
{
TreeNode right = node.right;
afterOrder(right);
}
System.out.println(node.value);
}
static int count = 0;
//递归计算节点数
public static int count(TreeNode node)
{
count++;
if(node.left!=null)
{
count(node.left);
}
if(node.right!=null)
{
count(node.right);
}
return count;
}
//递归计算高度
static int height = 0;
public static int height(TreeNode node)
{
if(node!=null)
{
height++;
}
if(node.left!=null)
{
height(node.left);
}else if(node.right!=null)
{
height(node.right);
}
return height;
}
}
class TreeNode{
int value;
TreeNode left;
TreeNode right;
public TreeNode(int value) {
this.value = value;
}
}
二叉树的创建和三种遍历方法(Java)
最新推荐文章于 2022-01-19 00:47:11 发布