# 二叉树 遍历方式

#### 二叉树的遍历方式

1.前序遍历 = 根左右，即先遍历根节点，再遍历左子树，最后遍历右子树；前序遍历上图所示的结果为ABDECF
2.中序遍历 = 左根右，即先遍历左子树，再遍历根节点，最后遍历右子树；中序遍历上图所示的结果为DBEAFC
3.后序遍历 = 左右根，即先遍历左子树，再遍历右子树，最后遍历根节点；后序遍历上图所示的结果为DEBFCA

#### Java代码示例

##### Node 结构
``````@Data
public class Node {

String data;
Node parent;
Node left;
Node right;

public Node(String data) {
this.data = data;
}
}
``````
##### 构建示例图中的二叉树结构 返回根节点A
``````public static Node buildRoot() {
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");
a.setLeft(b);
a.setRight(c);
b.setParent(a);
b.setLeft(d);
b.setRight(e);
c.setParent(a);
c.setLeft(f);
d.setParent(b);
e.setParent(b);
f.setParent(c);
return a;
}``````
##### 前序遍历
``````public static void front(Node root) {
if(root != null){
System.out.println(root.getData());
front(root.getLeft());
front(root.getRight());
}
}``````
##### 中序遍历
``````public static void middle(Node root) {
if (root != null) {
middle(root.getLeft());
System.out.println(root.getData());
middle(root.getRight());
}
}
``````
##### 后序遍历
``````public static void backend(Node root) {
if (root != null) {
backend(root.getLeft());
backend(root.getRight());
System.out.println(root.getData());
}
}
``````
##### 执行测试
``````public static void main(String[] args) {

System.out.print("前序:");
front(buildRoot());
System.out.println("");

System.out.print("中序:");
middle(buildRoot());
System.out.println("");

System.out.print("后序:");
backend(buildRoot());
}``````

27 声望
5 粉丝
0 条评论