根据访问节点的位置顺序,二叉树有4中遍历方式:
前序遍历:访问根结点的操作发生在遍历其左右子树之前。
中序遍历:访问根结点的操作发生在遍历其左右子树之中(间)。
后续遍历:访问根结点的操作发生在遍历其左右子树之后
层序遍历:将二叉树的每一层分别遍历,直到叶子节点全部被遍历完。
我们可以使用递归遍历二叉树。
前序遍历
if (root == null){
return;
}
System.out.print(root.value+" ");
binaryTreePrevOrder(root.left);
binaryTreePrevOrder(root.right);
中序遍历
void binaryTreeInOrder (TreeNode root){
if (root ==null){
return;
}
binaryTreeInOrder(root.left);
System.out.print(root.value+" ");
binaryTreeInOrder(root.right);
后序遍历
void binaryTreeOrder (TreeNode root){
if (root ==null){
return;
}
binaryTreeOrder(root.left);
binaryTreeOrder(root.right);
System.out.print(root.value+" ");
}