Java二叉树的遍历
对于如上二叉树,分别使用前序遍历、中序遍历、后序遍历遍历出它的每一个节点
在此之前,先新建一个节点类,节点类属性包含当前节点的数据(字符)、当前节点的左、右节点。
当不对一个节点的左右节点赋值,由于他们是成员变量且为引用类型,有初始值null,左右子树不赋值即左右子树都为null即为叶子结点
- 新建TreeNode节点类
public class TreeNode {
private String Data;
private TreeNode left;
private TreeNode right;
public String getData() {
return Data;
}
public void setData(String data) {
Data = data;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right = right;
}
public TreeNode(String data, TreeNode left, TreeNode right) {
super();
Data = data;
this.left = left;
this.right = right;
}
public TreeNode() {
super();
}
public TreeNode(String data) {
super();
Data = data;
}
@Override
public String toString() {
return Data;
}
}
- 遍历
对于前序遍历 先输出根节点 再输出左子树 最后输出右子树
对于输出子树可以用递归实现,当递归到节点为null递归结束
对于中序遍历 先输出左子树 再出根节点 最后输出右子树
对于输出子树可以用递归实现,当递归到节点为null递归结束
...
代码实现:
public class BinaryTreeErgodic {
public static void beforePre(TreeNode cur) {
if(cur==null) {
return;
}
System.out.print(cur+" ");
beforePre(cur.getLeft());
beforePre(cur.getRight());
}
public static void afterPre(TreeNode cur) {
if(cur==null) {
return;
}
afterPre(cur.getLeft());
afterPre(cur.getRight());
System.out.print(cur+" ");
}
public static void midPre(TreeNode cur) {
if(cur==null) {
return;
}
midPre(cur.getLeft());
System.out.print(cur+" ");
midPre(cur.getRight());
}
}
3.构建二叉树进行遍历
public static void main(String[] args) {
TreeNode a = new TreeNode("A");
TreeNode b = new TreeNode("B");
TreeNode c = new TreeNode("C");
TreeNode d = new TreeNode("D");
TreeNode e = new TreeNode("E");
TreeNode f = new TreeNode("F");
TreeNode g = new TreeNode("G");
TreeNode h = new TreeNode("H");
a.setLeft(b);a.setRight(c);
b.setLeft(d);b.setRight(f);
c.setLeft(g);c.setRight(h);
d.setLeft(e);
//BinaryTreeErgodic.afterPre(a);
//BinaryTreeErgodic.midPre(a);
//BinaryTreeErgodic.beforePre(a);
}