public class TreeNode {
public String val;//数据
public TreeNode left;//左孩子的引用,常常代表左孩子为根的整棵左子树
public TreeNode right;// 右孩子的引用,常常代表右孩子为根的整棵右子树
public TreeNode(String value) {
this.val = value;
}
//先序遍历
void xianxu(TreeNode root) {
if (root == null) {
return;
} else {
System.out.print(root.val + " ");
xianxu(root.left);
xianxu(root.right);
}
}
//中序遍历
void zhongxu(TreeNode root) {
if (root == null) {
return;
} else {
zhongxu(root.left);
System.out.print(root.val + " ");
zhongxu(root.right);
}
}
//后序遍历
void houxu(TreeNode root) {
if (root == null) {
return;
} else {
houxu(root.left);
houxu(root.right);
System.out.print(root.val + " ");
}
}
public static void main(String[] args) {
// 构建二叉树
TreeNode nodeA = new TreeNode("A");
TreeNode nodeB = new TreeNode("B");
TreeNode nodeC = new TreeNode("C");
TreeNode nodeD = new TreeNode("D");
TreeNode nodeE = new TreeNode("E");
TreeNode nodeF = new TreeNode("F");
TreeNode nodeG = new TreeNode("G");
nodeA.left = nodeB;
nodeA.right = nodeC;
nodeB.left = nodeD;
nodeB.right = nodeE;
nodeC.left = nodeF;
nodeC.right = nodeG;
// 先序遍历 根左右 A B D E C F G
// nodeA.xianxu(nodeA);
// 中序遍历 左根右 D B E A F C G
// nodeA.zhongxu(nodeA);
// 后序遍历 左右根 D E B F G C A
nodeA.houxu(nodeA);
}
}
java遍历二叉树
最新推荐文章于 2024-08-17 00:51:15 发布