二叉树前/先序DLR中序LDR后序LRD遍历及镜像翻转
一、名词释义
二叉树的遍历方式,根据遍历根节点的顺序不同,分为三种:前序(先序)遍历(DLR)、中序遍历(LDR)、后序遍历(LRD)。
【D:degree,节点拥有的子树的个数被称为节点的度,比如二叉树中每个有子树的父节点,都是有度的节点。 L:left R:right】
1、前序遍历【根-左-右】
2、中序遍历【左-根-右】
3、后序遍历【左-右-根】
4、镜像反转【将二叉树的每个左右子树互换】
二、执行代码
package com.dylanu.algorithm;
class BinaryTree{
BinaryTree left;
BinaryTree right;
Integer val;
public BinaryTree(Integer val) {
super();
this.val = val;
}
public BinaryTree getLeft() {
return this.left;
}
public BinaryTree getRight() {
return this.right;
}
public Integer getVal() {
return this.val;
}
}
public class BinaryTreeTest {
static StringBuilder stringBuilder = new StringBuilder();
public static void preOrderTraversal(BinaryTree root) {
if(null == root) {
return;
}
stringBuilder.append(root.getVal()).append("#");
preOrderTraversal(root.left);
preOrderTraversal(root.right);
}
public static void inOrderTraversal(BinaryTree root) {
if(null == root ) {
return;
}
inOrderTraversal(root.getLeft());
stringBuilder.append(root.getVal()).append("#");
inOrderTraversal(root.getRight());
}
public static void postOrderTraversal(BinaryTree root) {
if(null == root ) {
return;
}
postOrderTraversal(root.getLeft());
postOrderTraversal(root.getRight());
stringBuilder.append(root.getVal()).append("#");
}
public static void reversal(BinaryTree root) {
if(null == root ) {
return;
}
BinaryTree left = root.getLeft();
BinaryTree right = root.getRight();
reversal(left);
reversal(right);
root.left = right;
root.right = left;
}
public static void main(String[] args) {
BinaryTree root = new BinaryTree(6);
root.left = new BinaryTree(2);
root.left.left = new BinaryTree(1);
root.left.left.left = new BinaryTree(0);
root.left.right = new BinaryTree(4);
root.left.right.left = new BinaryTree(3);
root.left.right.right = new BinaryTree(5);
root.right = new BinaryTree(11);
root.right.left = new BinaryTree(7);
root.right.right = new BinaryTree(9);
root.right.right.left = new BinaryTree(8);
root.right.right.right = new BinaryTree(10);
inOrderTraversal(root);System.out.println(stringBuilder);
reversal(root);
stringBuilder = new StringBuilder();
inOrderTraversal(root);System.out.println(stringBuilder);
}
}
|