1、二叉树遍历主要三种遍历 :
1、先序遍历;
2、中序遍历;
3、后序遍历;
2、三种遍历方式的流程 :
先序遍历
中序遍历
后序遍历
3、递归
三种遍历方式
基础代码
public class TreeNode {
public TreeNode left;
public TreeNode right;
public String name;
}
3.1 先序遍历
public void preOrderTraversal(TreeNode node) {
if (node != null){
System.out.println(node.name);
preOrderTraversal(node.left);
preOrderTraversal(node.right);
}
}
3.2 中序遍历
public void preOrderTraversal(TreeNode node) {
if (node != null){
System.out.println(node.name);
preOrderTraversal(node.left);
preOrderTraversal(node.right);
}
}
3.3 后序遍历
public void preOrderTraversal(TreeNode node) {
if (node != null){
System.out.println(node.name);
preOrderTraversal(node.left);
preOrderTraversal(node.right);
}
}
4、代码实现三种遍历方式(非递归) :
基础代码
public class Stack {
private List<TreeNode> treeNodes = new ArrayList<>();
public void push(TreeNode node) {
treeNodes.add(node);
}
public TreeNode pop(){
TreeNode node = treeNodes.get(treeNodes.size()-1);
treeNodes.remove(node);
return node;
}
public boolean isEmpty() {
return treeNodes.isEmpty();
}
}
4.1 先序遍历
public void preOrderTraversal(TreeNode node) {
Stack stack = new Stack();
while(true) {
while(node != null) {
System.out.println(node.name);
stack.push(node);
node = node.left;
}
if(stack.isEmpty()) {
break;
}
node = stack.pop();
node = node.right;
}
}
4.2 中序遍历
public void inOrderTraversal(TreeNode node) {
Stack stack = new Stack();
while(true) {
while(node != null) {
stack.push(node);
node = node.left;
}
if(stack.isEmpty()) {
break;
}
node = stack.pop();
System.out.println(node.name);
node = node.right;
}
}
4.3 后序遍历
public void postOrderTraversal(TreeNode node) {
Stack stack = new Stack();
while(true) {
while(node != null) {
stack.push(node);
node = node.left;
}
if(stack.isEmpty()) {
break;
}
node = stack.pop();
if (node.right == null){
System.out.println(node.name);
}
node = node.right;
}
}